在非MVC环境下使用 Razor引擎

Razor引擎下载地址:

http://github.com/Antaris/RazorEngine

解析Model:

  string template = "Hello @Model.Name! Welcome to Razor!";
string result = Razor.Parse(template, new { Name = "World" });

使用Helper:

string template =
@"@helper MyMethod(string name) {
Hello @name
}
@MyMethod(Model.Name)! Welcome to Razor!";
string result = Razor.Parse(template, new { Name = "World" });

预编译:

string template = "Some really complex template that will take time to parse";

    Razor.Compile(template, "complex");
Razor.Run("complex");
Razor.Compile(template, typeof(SomeModel), "complex");
Razor.CompileWithAnonymous(template, "complex");

使用自定义模版:

public abstract class MyCustomTemplateBase<T> : TemplateBase<T>
{
public string ToUpperCase(string name)
{
return name.ToUpperCase();
}
} Razor.SetTemplateBase(typeof(MyCustomTemplateBase<>)); string template = "My name in UPPER CASE is: @ToUpperCase(Model.Name)";
string result = Razor.Parse(template, new { Name = "Matt" });
上一篇:关于Razor引擎的语法说明


下一篇:[asp.net mvc 奇淫巧技] 02 - 巧用Razor引擎在Action内生成Html代码