使用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>")

运行截图

预览


参考资料

posted @ 2020-06-24 14:30  地对地捣蛋的大号  阅读(507)  评论(0编辑  收藏  举报
c#/.net core