您的位置:首页 > 其它

Razor模板引擎

2015-10-23 12:57 253 查看
说明:基于ashx和html的示例

1、用法:

1.1、基本用法:方法Parse,对象@Model

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


1.2、指令Include,方法Compile

string template1 = "Hello";
string template2 = "@Model.Name This is my sample template, @Include(\"Template1\")";
Razor.Compile(template1, "Template1");
string result = Razor.Parse(template2, new { Name = "Wade" });


1.3、常用语法

选择语句:@if{}
循环语句:@for(int i=0;i<@Model.list.Count;i++){}
代码段:@{ var n = 0; }


1.4、输出@:

可以使用@@,也可以使用html的方式@


1.5、注释:

@<h1>1111</h1>@


2、示例:

test.html:

<body>
@Include("Top")
<h1>@Model.TypeTitle</h1>
<h2>@Model.TypeId</h2>
<hr />
@{
@*<h1>1111</h1>*@
for(int i=0;i<11;i++)
{
if(i%2==0)
{
<span>@i</span>
}
}
}
</body>


top.html:

<h1>Head</h1>


ashx:

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";

string top = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "RazorTest/top.html");
Razor.Compile(top, "Top");//替换目标字符串,与Include对应

string html = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "RazorTest/test.html");

html = Razor.Parse(html, new Model.TypeInfo()//替换对象,与Model对应
{
TypeTitle = "zhao",
TypeId = 1,
});
context.Response.Write(html);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: