ASP.NET MVC的Razor想必大家都比较熟悉,这里介绍一个独立于ASP.NET的RazorEngine。
RazorEngine是一个开源的项目,它的基础就是ASP.NET MVC的Razor。GitHub项目地址。
您可以在Windows Console或者Windows Forms使用它。
下面简单介绍如何使用。
1.创建一个Windows Console
2.通过NuGet安装RazorEngine

3.下面先介绍使用字符串替代cshtml文件模板的代码。
using RazorEngine;
using RazorEngine.Templating;
namespace RazorDemo.ConsoleDemo
{
class Program
{
static void Main(string[] args)
{
var template = "Hello @Model.Name, welcome to use RazorEngine!";
var result = Engine.Razor.RunCompile(template, "templateKey1", null, new { Name = "World" });
Console.WriteLine(result);
Console.Read();
}
}
}
运行程序,查看结果。
4.下面是使用cshtml文件作为模板的代码。
4.1添加一个Model文件夹,然后添加一个类UserInfo作为Model。
namespace RazorDemo.ConsoleDemo.Model
{
public class UserInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
4.2添加一个文件夹Templates,然后添加一个html文件,将扩展名改为cshtml。这个文件属性改为内容Content,总是拷贝Copy always。
@model RazorDemo.ConsoleDemo.Model.UserInfo
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Welcome</title>
</head>
<body>
<p>Hi @Model.FirstName @Model.LastName,</p>
<p>Welcome to use RazorEngine!</p>
</body>
</html>
4.3最后修改Main方法的代码。
using RazorEngine;
using RazorEngine.Templating;
using RazorDemo.ConsoleDemo.Model;
namespace RazorDemo.ConsoleDemo
{
class Program
{
static void Main(string[] args)
{
var path = AppDomain.CurrentDomain.BaseDirectory + "templates\hello.cshtml";
var template = File.ReadAllText(path);
var model = new UserInfo { FirstName = "Bill", LastName = "Gates" };
var result = Engine.Razor.RunCompile(template, "templateKey2", null, model);
Console.WriteLine(result);
Console.Read();
}
}
}
运行程序,查看结果。
运行程序的时候Console可能会输出一大串有关临时文件的信息,可以忽略。如果想去掉,请参考这里。
其实在后台RazorEngine将模板和模型结合后生成了一个对应的临时类文件,然后调用Execute方法生成最终结果。
namespace CompiledRazorTemplates.Dynamic
{
using System;
using System.Collections.Generic;
using System.Linq;
[RazorEngine.Compilation.HasDynamicModelAttribute()]
public class RazorEngine_77696eebc8a14ee8b43cc5e2d283e65a : RazorEngine.Templating.TemplateBase<RazorDemo.ConsoleDemo.Model.UserInfo>
{
public RazorEngine_77696eebc8a14ee8b43cc5e2d283e65a()
{
}
public override void Execute()
{
WriteLiteral("<!DOCTYPE html>
<html");
WriteLiteral(" lang="en"");
WriteLiteral(" xmlns="http://www.w3.org/1999/xhtml"");
WriteLiteral(">
<head>
<meta");
WriteLiteral(" charset="utf-8"");
WriteLiteral(" />
<title>Welcome</title>
</head>
<body>
<p>Hi ");
Write(Model.FirstName);
WriteLiteral(" ");
Write(Model.LastName);
WriteLiteral(",</p>
<p>Welcome to use RazorEngine!</p>
</body>
</html>
");
}
}
}
RazorEngine的用途很多,只要有模板(cshtml)和模型(Model)就可以使用。比如
1)制作一个代码生成器
2)生成邮件正文
如果不妥之处,请见谅。