C#模板引擎 RazorEngine3.7的简单使用

来源:互联网 发布:java如何打war包 编辑:程序博客网 时间:2024/05/16 15:35

RazorEngine是什么,可以用来做什么就不多介绍了,网上的说明还是很多的。

但网上大多的示例都是2.0版本的,RazorEngine的3.7版本还是改动很大的,有必要做下简单的记录。

可通过nuget将RazorEngine组件添加到程序中:Install-Package RazorEngine -Version 3.7.0

1. 简单的占位符替换

string template = "Hello @Model.Name, welcome to RazorEngine!";var result =     Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });

注意:"templateKey"必须是唯一的,并且运行以上实例后可以使用"templateKey"运行缓存模板:

var result = Engine.Razor.Run("templateKey", null, new { Name = "Max" });

2. 替换指定文件的内容

var config = new TemplateServiceConfiguration();using (var service = RazorEngineService.Create(config)){    string path1 = Server.MapPath("~/Template/cshtml/test3.cshtml");    string index = System.IO.File.ReadAllText(path1, System.Text.Encoding.UTF8);    var model = new { Name = "xiaoli" };    string result = service.RunCompile(index, string.Empty, null, model);}
注意:我这里使用RazorEngineService.Create创建了模板引擎服务的实例,这样的好处是,当我程序运行时修改test3.cshtml文件的内容时不会抛出"键已被使用"的异常。

3. 文件嵌套

一个网站页面通常包含许多公共的部分:head、top、bottom...

以下介绍如何在页面中引入这些公共的页面html

string path = Server.MapPath("~/Template/cshtml/include/header.cshtml");string header = System.IO.File.ReadAllText(path, System.Text.Encoding.UTF8);string path1 = Server.MapPath("~/Template/cshtml/test4.cshtml");string index = System.IO.File.ReadAllText(path1, System.Text.Encoding.UTF8);Engine.Razor.Compile(header, "Header");var result =     Engine.Razor.RunCompile(index, "templateKey", null, new { Title = "测试", Name = "xiaoli" });

header.cshtml:

<head>    <meta name="viewport" content="width=device-width" />    <title>Header</title></head>
test4.cshtml:

<html>@Include("Header", Model)<body>    <div>        Name is @Model.Name    </div></body></html> 

4. 添加自定义方法

    public abstract class MyCustomTemplateBase<T> : TemplateBase<T>    {        public MyCustomTemplateBase()        {            this.StringHelper = new StringHelper();        }        public StringHelper StringHelper { get; set; }    }    /// <summary>    /// 字符串帮助类    /// </summary>    public class StringHelper    {        /// <summary>        /// 字符串转换为大写        /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public string ToUpper(string str)        {            return str.ToUpper();        }    }

后台方法:

var config = new TemplateServiceConfiguration();config.BaseTemplateType = typeof(MyCustomTemplateBase<>);using (var service = RazorEngineService.Create(config)){    string path1 = Server.MapPath("~/Template/cshtml/test3.cshtml");    string index = System.IO.File.ReadAllText(path1, System.Text.Encoding.UTF8);    var model = new { Name = "xiaoli" };    string result = service.RunCompile(index, string.Empty, null, model);}

视图页:

<div>    Name is @StringHelper.ToUpper(Model.Name)</div>


更多参考:

抛弃NVelocity,来玩玩Razor

Antaris/RazorEngine · GitHub


Demo下载:

RazorEngine3.7示例

0 0
原创粉丝点击