Razor模板引擎

Razor模板引擎

Razor模板引擎使用

模板引擎:Razor、Nvelocity、Vtemplate。 Razor有VS自动提示,而且有助于学习asp.net mvc。
借助于开源的RazorEngine,我们可以在非asp.net mvc项目中使用Razor引擎,甚至在控制台、WinForm项目中都可以使用Razor(自己开发代码生成器)
在非mvc项目中创建Razor文件(cshtml ,可以利用自动提示)的方法,新建一个html,改名为cshtml。
Razor中@后面跟表达式表示在这个位置输出表达式的值,模板中Model为传递给模板的对象。
@{}中为C#代码,C#代码还可以和html代码混排
由于不是在MVC项目中,所以无法使用@Html.DropDownList、@Url.Encode()等。

解析razor文件

1 public static string Parse(HttpContext context, string fileVirtualPath, object model)
2         {
3             string fullPath = context.Server.MapPath(fileVirtualPath);
4             string cacheName =
5                        fileVirtualPath+File.GetLastWriteTime(fullPath).ToString();
6             string result = Razor.Parse(File.ReadAllText(fullPath), model, cacheName);
7             return result;
8         }

 关于cacheName

cacheName写成一个固定的值,当cshtml发生改变的时候Parse的结果也是修改后的内容

经过反编译发现Parse方法最终调用的是TemplateService的GetTemplate方法,代码如下:

 1 private ITemplate GetTemplate<T>(string razorTemplate, object model, string cacheName)
 2 {
 3     Func<string, CachedTemplateItem, CachedTemplateItem> updateValueFactory = null;
 4     CachedTemplateItem item;
 5     if (razorTemplate == null)
 6     {
 7         throw new ArgumentNullException("razorTemplate");
 8     }
 9     int hashCode = razorTemplate.GetHashCode();
10     if (!this._cache.TryGetValue(cacheName, out item) || (item.CachedHashCode != hashCode))
11     {
12         Type templateType = this.CreateTemplateType(razorTemplate, (model == null) ? typeof(T) : model.GetType());
13         item = new CachedTemplateItem(hashCode, templateType);
14         if (updateValueFactory == null)
15         {
16             updateValueFactory = (n, i) => item;
17         }
18         this._cache.AddOrUpdate(cacheName, item, updateValueFactory);
19     }
20     return this.CreateTemplate(null, item.TemplateType, model);
21 }

代码大意是:从缓存cache中查找是否有名字等于cacheName的缓存项“TryGetValue(cacheName, out item)”,如果不存在,则编译创建;如果存在,则再检查缓存中的cshtml内容的hashCode(字符串的特征码,相同的字符串的HashCode一样,不同字符串的HashCode有一样的概率)和这次传进来的razorTemplate的HashCode是否一样,如果不一样也重新编译创建,而不使用缓存的。

Razor调用外部方法

 1  public static RawString raw(string name, string id, bool isChenk)
 2         {
 3             StringBuilder sb = new StringBuilder();
 4             sb.Append("<input type='checkbox' id='").Append(id).Append("' name='").Append(name).Append("'");
 5             if (isChenk)
 6             {
 7                 sb.Append("checked");
 8             }
 9             sb.Append("/>");
10             return new RawString(sb.ToString());
11         }
 1 @using Razor2;
 2 <!DOCTYPE html>
 3 <html xmlns="http://www.w3.org/1999/xhtml">
 4 <head>
 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 6     <title></title>
 7 </head>
 8 <body>
 9         @Razor2.raw("c1", "c2", false)
10 </body>
11 </html>

@后面的表达式如果是string类型,那么输出的时候就会自动进行htmlEncode。如果不想进行htmlencode的显示,则可以自己封装一个Raw方法:

public static RawString Raw(string str)

        {

            return new RawString(str);

        }

然后@RPHelper.Raw(Model.Html)

posted on 2015-08-22 19:53  Mr.Tan&  阅读(775)  评论(0编辑  收藏  举报

导航