zoukankan      html  css  js  c++  java
  • 使用Razor引擎模板生成字符串

    使用Razor引擎模板生成字符串,类似于T4模板,T4要学语法,Razor就是就用c#了


    安装依赖包

    Install-Package RazorEngine.NetCore
    

    生成代码

    class Program
    {
        static void Main(string[] args)
        {
            //简单使用
            string template = "Hello @Model.Name, welcome to RazorEngine!";
            var result = Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });
            Console.WriteLine(result);
    
            //带html标签
            string template1 = "@Raw(Model.Data)";
            var model1 = new { Data = "My raw double quotes <p>appears</p> here "hello!"" };
    
            string result1 = Engine.Razor.RunCompile(template1, "templateKey1", null, model1);
    
            Console.WriteLine(result1);
    
            //使用模板文件
            string filePath = "StudentTemplate.cshtml";
            var userTemplate= File.ReadAllText(filePath);
            string result2= Engine.Razor.RunCompile(userTemplate, Guid.NewGuid().ToString(), typeof(User), new User
            {
                CreateTime = DateTime.Now,
                EmailAddress = "<p>125880321@qq.com</p>",
                UserName = "IGeekFan"
            });
            Console.WriteLine(result2);
        }
    }
    public class User
    {
        public string UserName { get; set; }
        public string EmailAddress { get; set; }
        public DateTime CreateTime { get; set; }
    }
    

    cshtml模板

    @{
        var gen = Model as RazorTemplate.User;
    }
    
    //=============================================================
    // 创建人:            @gen.UserName
    // 创建时间:          @gen.CreateTime
    // 邮箱:             @gen.EmailAddress
    //==============================================================
    <h1>123</h1>
    @Raw("<a>www.baidu.com<a>")
    

    运行截图

    预览


    参考资料

  • 相关阅读:
    Dockerfile构建镜像
    00基础复习
    docker的网络(基础)
    02-Mysql中的运算符
    01-mysql中的数据类型
    Docker客户端连接Docker Daemon的方式
    docker-ce快速部署
    ubuntu18.04 server配置静态ip
    html语义化小记录
    webpack导入es6的简单应用
  • 原文地址:https://www.cnblogs.com/missile/p/13187341.html
Copyright © 2011-2022 走看看