首页 > 代码库 > Razor - 模板引擎 / 代码生成 - RazorEngine

Razor - 模板引擎 / 代码生成 - RazorEngine

目录

  • Brief
  • Authors
  • Official Website
  • RazorEngine 的原理 - 官方解释
  • 安装记录
  • Supported Syntax (默认实现支持的语法)
  • 测试记录 - can‘t cleanup temp files
  • 测试记录 - Quick Start
  • 测试记录 - Configuration
  • 测试记录 - 对比 3 种 Type 的 model 的语法
  • 测试记录 - 扩展模板语法
  • 测试记录 - Layout
  • 测试记录 - Partial (@Include())
  • Encoding Values - @Raw()
  • RazorEngine.Razor 已废弃,请改用 Engine.Razor
  • 缓存
  • 作者说: 无法稍毁缓存
  • 某网文代码
  • 安全 - 只可能内部使用、不能让用户定义模板
  • Resource - Hello World
  • Resource - Advanced
  • base or advanced

Brief

Open source templating engine based on Microsoft‘s Razor parsing engine.

Authors

  • Matthew Abbott
  • Ben Dornis
  • Matthias Dittrich

Official Website

GitHub

  • http://github.com/Antaris/RazorEngine
  • http://github.com/Antaris/RazorEngine#quickstart - quick start
  • http://antaris.github.io/RazorEngine - latest documentation available (官方文档 - 截至 2016-07-24 能找到的最好的文档)
  • http://antaris.github.io/RazorEngine/ReferenceResolver.html - Reference Resolver - 截至 2016-08-20 暂未遇到应用场景,留待有需要时再深入研究。
  • http://antaris.github.io/RazorEngine/Isolation.html - RazorEngine Isolation API - 截至 2016-08-20 暂未遇到应用场景,留待有需要时再深入研究。
  • Resolving and Caching Templates
  • http://antaris.github.io/RazorEngine/TemplateManager.html - ITemplateManager and ICachingProvider - 截至 2016-08-21 暂未遇到应用场景,留待有需要时再深入研究。
  • http://antaris.github.io/RazorEngine/Upgrading.html - Upgrading RazorEngine
  • http://antaris.github.io/RazorEngine/IntellisenseAndResharper.html - Intellisense and ReSharper
  • http://antaris.github.io/RazorEngine/references/index.html - references

CodePlex - obsolete

  • http://razorengine.codeplex.com/
  • http://razorengine.codeplex.com/documentation

NuGet

Install-Package RazorEngine
Install-Package RazorEngine -Version 3.6.4
https://www.nuget.org/packages/RazorEngine/ - latest: RazorEngine 3.6.4, Friday, March 27 2015

Stack Overflow

  • http://stackoverflow.com/search?q=RazorEngine - 1,100 results at 2016-08-14
  • http://stackoverflow.com/questions/tagged/razorengine

RazorEngine 的原理 - 官方解释

There is often a confusion about where Razor sits in this set of technologies. Essentially Razor is the parsing framework that does the work to take your text template and convert it into a compilable class. In terms of MVC and WebPages, they both utilise this parsing engine to convert text templates (view/page files) into executable classes (views/pages). Often we are asked questions such as "Where is @Html, @Url", etc. These are not features provided by Razor itself, but implementation details of the MVC and WebPages frameworks.

RazorEngine is another consumer framework of the Razor parser. We wrap up the instantiation of the Razor parser and provide a common framework for using runtime template processing.

-- Razor vs. MVC vs. WebPages vs. RazorEngine

安装记录

Installed into Net451Console via NuGet at 2016-07-31:

  1. ------- 正在安装...RazorEngine 3.9.0 -------
  2. 正在尝试解析依赖项“Microsoft.AspNet.Razor (≥ 3.0.0)”。
  3. 正在安装“Microsoft.AspNet.Razor 3.0.0”。
  4. 已将文件“System.Web.Razor.dll”添加到文件夹“Microsoft.AspNet.Razor.3.0.0\lib\net45”。
  5. 已将文件“System.Web.Razor.xml”添加到文件夹“Microsoft.AspNet.Razor.3.0.0\lib\net45”。
  6. 已将文件“Microsoft.AspNet.Razor.3.0.0.nuspec”添加到文件夹“Microsoft.AspNet.Razor.3.0.0”。
  7. 已将文件“Microsoft.AspNet.Razor.3.0.0.nupkg”添加到文件夹“Microsoft.AspNet.Razor.3.0.0”。
  8. 已成功安装“Microsoft.AspNet.Razor 3.0.0”。
  9. 正在安装“RazorEngine 3.9.0”。
  10. 已将文件“RazorEngine.dll”添加到文件夹“RazorEngine.3.9.0\lib\net40”。
  11. 已将文件“RazorEngine.xml”添加到文件夹“RazorEngine.3.9.0\lib\net40”。
  12. 已将文件“RazorEngine.dll”添加到文件夹“RazorEngine.3.9.0\lib\net45”。
  13. 已将文件“RazorEngine.xml”添加到文件夹“RazorEngine.3.9.0\lib\net45”。
  14. 已将文件“LICENSE.md”添加到文件夹“RazorEngine.3.9.0”。
  15. 已将文件“RazorEngine.3.9.0.nuspec”添加到文件夹“RazorEngine.3.9.0”。
  16. 已将文件“RazorEngine.3.9.0.nupkg”添加到文件夹“RazorEngine.3.9.0”。
  17. 已成功安装“RazorEngine 3.9.0”。
  18. 正在将“Microsoft.AspNet.Razor 3.0.0”添加到 Console
  19. 已将引用“System.Web.Razor”添加到项目“Console
  20. 已添加文件“packages.config”。
  21. 已将文件“packages.config”添加到项目“Console
  22. 已成功将“Microsoft.AspNet.Razor 3.0.0”添加到 Console
  23. 正在将“RazorEngine 3.9.0”添加到 Console
  24. 已将引用“RazorEngine”添加到项目“Console
  25. 已添加文件“packages.config”。
  26. 已成功将“RazorEngine 3.9.0”添加到 Console
  27. ==============================

总结: 共安装了两个 DLL: System.Web.Razor.dllRazorEngine.dll

Supported Syntax (默认实现支持的语法)

You can access several things when you use the default TemplateBase<> implementation:
@using Custom.Namespace (see also the quick intro and assembly resolvers for custom references)
@model ModelType
@inherits HtmlSupportTemplateBase<ModelType> (see below)
* Set a layout (and @RenderBody() within the layout template): @{ Layout = "layout.cshtml"; }
@Include("templateName", model = null, modelType = null) to include another template.
* Accessing the ViewBag: <h1>@ViewBag.Title</h1>
* Sections (@DefineSection@RenderSection and @IsSectionDefined)

-- http://antaris.github.io/RazorEngine/TemplateBasics.html#Supported-syntax

测试记录 - can‘t cleanup temp files

2015-10-19 Tony 在 .NET4.51 Console Application 中单步执行以下代码时弹出命令行窗口显示以下信息:

代码:

  1. using RazorEngine;
  2. using RazorEngine.Templating;
  3. namespace Net451ConsoleApplication
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. // using RazorEngine.Templating; // Dont forget to include this.
  10. string template = "Hello @Model.Name, welcome to RazorEngine!";
  11. var result = Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });
  12. }
  13. }
  14. }

信息:

  1. RazorEngine: We can‘t cleanup temp files if you use RazorEngine on the default Appdomain.
  2. Create a new AppDomain and use RazorEngine from there.
  3. Read the quickstart or https://github.com/Antaris/RazorEngine/issues/244 for details!
  4. You can ignore this and all following ‘Please clean ... manually‘ messages if you are using DisableTempFileLocking, which is not recommended.
  5. Please clean ‘C:\Users\User0\AppData\Local\Temp\RazorEngine_********.***‘ manually!

每次单步执行 RazorEngine.Engine.Razor.RunCompile() 后,都会生成 1 个目录及该目录中的 6 个文件,该目录及其中的全部文件的名称都是随机的,例如:

  1. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\CompiledRazorTemplates.Dynamic.RazorEngine_290440367cc04e8c9d06a99a7a805d08.dll"
  2. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\filbbops.0.cs"
  3. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\filbbops.cmdline"
  4. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\filbbops.err"
  5. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\filbbops.out"
  6. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\filbbops.tmp"

单步执行完毕后 (Tony 理解为应用程序域已终止并释放),其它 5 个文件已自动移除,但 .dll 文件及该目录会残留。以下为 4 次单步执行后的残留:

  1. "C:\Users\User0\AppData\Local\Temp\RazorEngine_bmze52rx.ovb\CompiledRazorTemplates.Dynamic.RazorEngine_a291215db8fd497cae3e4a2bfcabe7b2.dll"
  2. "C:\Users\User0\AppData\Local\Temp\RazorEngine_tkidehx4.qay\CompiledRazorTemplates.Dynamic.RazorEngine_bd299256d8b94f64ba943c5a09014ed6.dll"
  3. "C:\Users\User0\AppData\Local\Temp\RazorEngine_a1anyws2.vvo\CompiledRazorTemplates.Dynamic.RazorEngine_f890b330f6104de19631e25ea528a6e8.dll"
  4. "C:\Users\User0\AppData\Local\Temp\RazorEngine_pv3sxecv.dyv\CompiledRazorTemplates.Dynamic.RazorEngine_290440367cc04e8c9d06a99a7a805d08.dll"

官网提供了上述问题的解决方案,2017-03-15 编写以下代码对该方案进行了测试,结论: 该方案在控制台程序中有效:

  1. //Program.cs
  2. using RazorEngine;
  3. using RazorEngine.Templating;
  4. namespace Net451Console
  5. {
  6. class Program
  7. {
  8. //static void Main(string[] args)
  9. static int Main(string[] args)
  10. {
  11. bool isDefaultAppDomain = NewDomain.Switch();
  12. if(isDefaultAppDomain) {
  13. return 0;
  14. }
  15. #region test code:
  16. string template = "Hello @Model.Name, welcome to RazorEngine!";
  17. var result = Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });
  18. //执行上一行后创建了 "C:\Users\User0\AppData\Local\Temp\RazorEngine_tbr5ujmj.fju" 目录及其中的 6 个文件。
  19. var isTrue = result == "Hello World, welcome to RazorEngine!";
  20. #endregion test code.
  21. return 123;
  22. }
  23. //退出 Main() 后 "C:\Users\User0\AppData\Local\Temp\RazorEngine_tbr5ujmj.fju" 目录被删除。
  24. }
  25. }
  1. //NewDomain.cs
  2. using System;
  3. using System.Reflection;
  4. using System.Security;
  5. using System.Security.Permissions;
  6. using System.Security.Policy;
  7. namespace Net451Console
  8. {
  9. class NewDomain
  10. {
  11. /// <summary>
  12. /// 如果 应用程序域 非 进程的默认应用程序域,则 不作任何处理、直接返回 false;
  13. /// 如果 应用程序域 是 进程的默认应用程序域,则 创建新的应用程序域、并在该域中执行当前程序集、接着卸载该域、并返回 true。
  14. /// </summary>
  15. public static bool Switch()
  16. {
  17. bool isDefaultAppDomain = AppDomain.CurrentDomain.IsDefaultAppDomain();
  18. if(!isDefaultAppDomain) {
  19. return false;
  20. }
  21. // RazorEngine cannot clean up from the default appdomain...
  22. Console.WriteLine("Switching to second AppDomain, for RazorEngine...");
  23. //2017-03-15 已测试证明以下两行代码无用:
  24. //AppDomainSetup adSetup = new AppDomainSetup();
  25. //adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
  26. //测试记录: 至此 adSetup.ApplicationBase 的值为 "D:\Test\Net451Console\branches\RazorEngine\Net451Console\bin\Debug\"。
  27. // You only need to add strongnames when your appdomain is not a full trust environment.
  28. AppDomain domain = AppDomain.CreateDomain(
  29. "MyMainDomain",
  30. null,
  31. AppDomain.CurrentDomain.SetupInformation,
  32. new PermissionSet(PermissionState.Unrestricted),
  33. new StrongName[0]
  34. );
  35. string location = Assembly.GetExecutingAssembly().Location;
  36. //测试记录: 至此 location 的值为 "D:\Test\Net451Console\branches\RazorEngine\Net451Console\bin\Debug\Net451Console.exe"。
  37. int exitCode = domain.ExecuteAssembly(location);
  38. //执行上一行的 domain.ExecuteAssembly() 导致重新执行 Main(),届时 isDefaultAppDomain 为 false,将跳过本方法主体转而执行 Mian() 中的剩余代码,Main() 的返回值将成为上一行的返回值并赋给 exitCode,接着执行下 2 行代码,最后退出本方法。
  39. // Note that you need to Unload the domain to trigger cleanup.
  40. // RazorEngine will cleanup.
  41. AppDomain.Unload(domain);
  42. //执行上一行后 "C:\Users\User0\AppData\Local\Temp\RazorEngine_tbr5ujmj.fju" 目录中的 6 个文件仅剩下 1 个 .dll 文件。
  43. return true;
  44. }
  45. }
  46. }

测试记录 - 以上方案仅在控制台程序中有效、在 ASP.NET MVC 中无效

  1. 在 ASP.NET MVC 中 AppDomain.CurrentDomain.IsDefaultAppDomain() 总是返回 false
  2. 执行 Assembly.GetExecutingAssembly().Location 返回 C:\Users\User0\AppData\Local\Temp\Temporary ASP.NET Files\root\b54c3416\14425600\assembly\dl3\57a31749\d172b5e9_d29fd201\Net451MvcNoAuth.dll,接着执行下一行 domain.ExecuteAssembly(location) 报错 异常详细信息: System.MissingMethodException: 未在程序集“Net451MvcNoAuth, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中找到入口点。

测试记录 - Quick Start

以下测试代码整理自 http://antaris.github.io/RazorEngine/index.html#Quickstart:

  1. using RazorEngine;
  2. using RazorEngine.Templating;
  3. namespace Net451Console
  4. {
  5. class Program
  6. {
  7. //static void Main(string[] args)
  8. static int Main(string[] args)
  9. {
  10. bool isDefaultAppDomain = NewDomain.Switch();
  11. if(isDefaultAppDomain) {
  12. return 0;
  13. }
  14. #region test code:
  15. //All you need to do is use the static Engine class (the Engine.Razor instance) in the ‘RazorEngine‘ namespace:
  16. string template = "Hello @Model.Name, welcome to RazorEngine!";
  17. string key = "templateKey";
  18. var result0 = Engine.Razor.RunCompile(template, key, null, new { Name = "World" });
  19. //The "templateKey" must be unique and after running the above example you can re-run the cached template with this key.
  20. var result1 = Engine.Razor.Run(key, null, new { Name = "Max" });
  21. //The null parameter is the modelType and null in this case means we use dynamic as the type of the model. You can use a static model as well by providing a type object.
  22. var result2 = Engine.Razor.RunCompile(key, typeof(Person), new Person { Name = "Max" });
  23. //Note that we now re-compile the model with a different type. When you do not run the same template a lot of times (like several 1000 times), compiling uses the most time. So the benefit you get from a static type will most likely not compensate the additional compile time. Therefore you should either stick to one type for a template (best of both worlds) or just use (the slower) dynamic (null). You can specify the modelType of a template with the @model directive. When you do this the modelType parameter is ignored, but you should use the same type instance (or null) on every call to prevent unnecessary re-compilations because of type mismatches in the caching layer.
  24. #endregion test code.
  25. return 123;
  26. }
  27. }
  28. public class Person
  29. {
  30. public string Name { get; set; }
  31. }
  32. }

测试记录 - Configuration

以下测试代码整理自 http://antaris.github.io/RazorEngine/index.html#Configuration:

  1. using RazorEngine;
  2. using RazorEngine.Configuration;
  3. using RazorEngine.Templating;
  4. using RazorEngine.Text;
  5. namespace Net451Console
  6. {
  7. class Program
  8. {
  9. //static void Main(string[] args)
  10. static int Main(string[] args)
  11. {
  12. bool isDefaultAppDomain = NewDomain.Switch();
  13. if(isDefaultAppDomain) {
  14. return 0;
  15. }
  16. #region test code:
  17. //You can configure RazorEngine with the TemplateServiceConfiguration class.
  18. var config = new TemplateServiceConfiguration();
  19. // ... configure your instance
  20. //General Configuration
  21. //By default RazorEngine is configured to encode using Html. This supports the majority of users but with some configuration changes you can also set it to encode using Raw format which is better suited for templates that generate things like javascript, php, C# and others.
  22. config.Language = Language.CSharp; // C# as template language.
  23. config.EncodedStringFactory = new RawStringFactory(); // Raw string encoding.
  24. //config.EncodedStringFactory = new HtmlEncodedStringFactory(); // Html encoding.
  25. //One thing you might want to enable is the debugging feature:
  26. config.Debug = true;
  27. IRazorEngineService service = RazorEngineService.Create(config);
  28. //If you want to use the static Engine class with this new configuration:
  29. Engine.Razor = service;
  30. //When Debug is true you can straight up debug into the generated code. RazorEngine also supports debugging directly into the template files (normally .cshtml files). As as you might see in the above code there is no file to debug into. To provide RazorEngine with the necessary information you need to tell where the file can be found:
  31. string template = "Hello @Model.Name, welcome to RazorEngine!";
  32. string templateFile = "d:/mytemplate.cshtml";
  33. // Provide a non-null file to improve debugging
  34. var loadedTemplateSource = new LoadedTemplateSource(template, templateFile);
  35. var result = Engine.Razor.RunCompile(loadedTemplateSource, "templateKey", null, new { Name = "World" });
  36. //This time when debugging the template you will jump right into the template file.
  37. #endregion test code.
  38. return 123;
  39. }
  40. }
  41. }

上述代码中的 d:/mytemplate.cshtml 的测试记录:

  • 该文件中的断点有效。
  • 该文件的内容与 template 的值无关。
  • 该文件的内容可为任意字符 (包括空文件)。
  • 该文件不能放在 Windows10 的 C 分区,否则会因为访问权限而报错。

测试记录 - 对比 3 种 Type 的 model 的语法

以下测试代码整理自 http://antaris.github.io/RazorEngine/TemplateBasics.html:

  1. using RazorEngine;
  2. using RazorEngine.Templating;
  3. using System.Dynamic;
  4. namespace Net451Console
  5. {
  6. class Program
  7. {
  8. //static void Main(string[] args)
  9. static int Main(string[] args)
  10. {
  11. bool isDefaultAppDomain = NewDomain.Switch();
  12. if(isDefaultAppDomain) {
  13. return 0;
  14. }
  15. #region test code:
  16. string template = "<div>Hello @Model.Name</div>";
  17. var model0 = new Person { Name = "Matt" }; //statically type
  18. var model1 = new { Name = "Matt" }; //anonymous type
  19. dynamic model2 = new ExpandoObject(); //dynamic type
  20. model2.Name = "Matt"; //dynamic type
  21. string result0 = Engine.Razor.RunCompile(template, "key0", typeof(Person), model0); //statically type
  22. string result1 = Engine.Razor.RunCompile(template, "key1", null, model1); //anonymous type
  23. string result2 = Engine.Razor.RunCompile(template, "key2", null, (object)model2); //dynamic type
  24. //执行至此 result0-2 均为 "<div>Hello Matt</div>"。
  25. #endregion test code.
  26. return 123;
  27. }
  28. }
  29. public class Person
  30. {
  31. public string Name { get; set; }
  32. }
  33. }

测试记录 - 扩展模板语法

以下测试代码整理自 http://antaris.github.io/RazorEngine/TemplateBasics.html#Extending-the-template-Syntax:

  1. using RazorEngine.Configuration;
  2. using RazorEngine.Templating;
  3. using RazorEngine.Text;
  4. using System;
  5. namespace Net451Console
  6. {
  7. class Program
  8. {
  9. //static void Main(string[] args)
  10. static int Main(string[] args)
  11. {
  12. bool isDefaultAppDomain = NewDomain.Switch();
  13. if(isDefaultAppDomain) {
  14. return 0;
  15. }
  16. #region test code:
  17. var config = new TemplateServiceConfiguration();
  18. // You can use the @inherits directive instead (this is the fallback if no @inherits is found).
  19. config.BaseTemplateType = typeof(HtmlSupportTemplateBase<>);
  20. using(var service = RazorEngineService.Create(config)) {
  21. string template0 = "@Model.Data";
  22. string template1 = "@Html.Raw(Model.Data)";
  23. string data = "My raw double quotes appears here \"hello!\"";
  24. var model = new { Data = data };
  25. string result0 = service.RunCompile(template0, "htmlRawTemplate0", null, model);
  26. string result1 = service.RunCompile(template1, "htmlRawTemplate1", null, model);
  27. if(result0 == "My raw double quotes appears here "hello!"") {
  28. Console.WriteLine("* 默认行为: 引号被 HTML 实体编码。");
  29. }
  30. if(result1 == data) {
  31. Console.WriteLine("* @Html.Raw() 原样输出。");
  32. }
  33. }
  34. #endregion test code.
  35. return 123;
  36. }
  37. }
  38. public class MyHtmlHelper
  39. {
  40. public IEncodedString Raw(string rawString)
  41. {
  42. return new RawString(rawString);
  43. }
  44. }
  45. public abstract class HtmlSupportTemplateBase<T> : TemplateBase<T>
  46. {
  47. //public MyClassImplementingTemplateBase()
  48. public HtmlSupportTemplateBase()
  49. {
  50. Html = new MyHtmlHelper();
  51. }
  52. public MyHtmlHelper Html { get; set; }
  53. }
  54. }

测试记录 - Layout

以下测试代码整理自 http://antaris.github.io/RazorEngine/LayoutAndPartial.html#Layout-template:

  1. using RazorEngine;
  2. using RazorEngine.Templating;
  3. namespace Net451Console
  4. {
  5. class Program
  6. {
  7. //static void Main(string[] args)
  8. static int Main(string[] args)
  9. {
  10. bool isDefaultAppDomain = NewDomain.Switch();
  11. if(isDefaultAppDomain) {
  12. return 0;
  13. }
  14. #region test code:
  15. IRazorEngineService service = Engine.Razor;
  16. service.AddTemplate("Layout0", @"<html>@RenderBody()</html>");
  17. service.AddTemplate("Layout1", @"<body>@RenderBody()</body>@{ Layout = ""Layout0""; }");
  18. service.AddTemplate("Layout2", @"<div> @RenderBody()</div> @{ Layout = ""Layout1""; }");
  19. service.AddTemplate("templet", @"<h1> content in h1</h1> @{ Layout = ""Layout2""; }");
  20. service.Compile("templet");
  21. string result = service.Run("templet");
  22. bool isTrue = result == "<html><body><div> <h1> content in h1</h1> </div> </body></html>";
  23. #endregion test code.
  24. return 123;
  25. }
  26. }
  27. }

测试记录 - Partial (@Include())

以下测试代码整理自 http://antaris.github.io/RazorEngine/LayoutAndPartial.html#Partial-templates:

  1. using RazorEngine;
  2. using RazorEngine.Templating;
  3. namespace Net451Console
  4. {
  5. class Program
  6. {
  7. //static void Main(string[] args)
  8. static int Main(string[] args)
  9. {
  10. bool isDefaultAppDomain = NewDomain.Switch();
  11. if(isDefaultAppDomain) {
  12. return 0;
  13. }
  14. #region test code:
  15. var service = Engine.Razor;
  16. service.AddTemplate("part", @"my template");
  17. // If you leave the second and third parameters out the current model will be used.
  18. // If you leave the third we assume the template can be used for multiple types and use "dynamic".
  19. // If the second parameter is null (which is default) the third parameter is ignored.
  20. // To workaround in the case you want to specify type "dynamic" without specifying a model use Include("p", new object(), null)
  21. service.AddTemplate("template", @"<h1>@Include(""part"", @Model.SubModel, typeof(Net451Console.SubModel))</h1>");
  22. service.Compile("template", typeof(MyModel));
  23. service.Compile("part", typeof(SubModel));
  24. var result = service.Run(
  25. "template",
  26. typeof(MyModel),
  27. new MyModel {
  28. ModelProperty = "model",
  29. SubModel = new SubModel { SubModelProperty = "submodel" }
  30. }
  31. );
  32. bool isTrue = result == "<h1>my template</h1>";
  33. #endregion test code.
  34. return 123;
  35. }
  36. }
  37. public class SubModel
  38. {
  39. public string SubModelProperty { get; set; }
  40. }
  41. public class MyModel
  42. {
  43. public string ModelProperty { get; set; }
  44. public SubModel SubModel { get; set; }
  45. }
  46. }

测试发现很多参数都可省略:

  1. using RazorEngine;
  2. using RazorEngine.Templating;
  3. namespace Net451Console
  4. {
  5. class Program
  6. {
  7. //static void Main(string[] args)
  8. static int Main(string[] args)
  9. {
  10. bool isDefaultAppDomain = NewDomain.Switch();
  11. if(isDefaultAppDomain) {
  12. return 0;
  13. }
  14. #region test code:
  15. var service = Engine.Razor;
  16. service.AddTemplate("part", @"Text in the part.");
  17. service.AddTemplate("template", @"<h1>@Include(""part"")</h1>");
  18. service.Compile("template");
  19. service.Compile("part");
  20. var result = service.Run("template");
  21. bool isTrue = result == "<h1>Text in the part.</h1>";
  22. #endregion test code.
  23. return 123;
  24. }
  25. }
  26. }

Encoding Values - @Raw()

以下测试代码整理自 http://antaris.github.io/RazorEngine/Encoding.html:

  1. using RazorEngine;
  2. using RazorEngine.Templating;
  3. namespace Net451Console
  4. {
  5. class Program
  6. {
  7. //static void Main(string[] args)
  8. static int Main(string[] args)
  9. {
  10. bool isDefaultAppDomain = NewDomain.Switch();
  11. if(isDefaultAppDomain) {
  12. return 0;
  13. }
  14. #region test code:
  15. //By default RazorEngine is configured to encode as Html. This sometimes this presents problems were certain characters are encoded as Html but what you want is to output them as-is. To output something in raw format use the @Raw() built-in method as shown in the following example:
  16. string template0 = "@Model.Data";
  17. string template1 = "@Raw(Model.Data)";
  18. var model = new { Data = "My raw double quotes appears here \"hello!\"" };
  19. string result0 = Engine.Razor.RunCompile(template0, "templateKey0", null, model);
  20. string result1 = Engine.Razor.RunCompile(template1, "templateKey1", null, model);
  21. bool isTrue0 = result0 == @"My raw double quotes appears here "hello!"";
  22. bool isTrue1 = result1 == @"My raw double quotes appears here ""hello!""";
  23. #endregion test code.
  24. return 123;
  25. }
  26. }
  27. }

测试记录 - 不支持 @Html.Raw()

执行 string test = Engine.Razor.RunCompile(@"@Html.Raw(""asdf"")", "key", null, string.Empty); 时抛出异常 "当前上下文中不存在名称“Html”"。

RazorEngine.Razor 已废弃,请改用 Engine.Razor

  1. #region 程序集 RazorEngine.dll, v3.9.0.0
  2. // D:\Test\Net451Console\branches\RazorEngine\packages\RazorEngine.3.9.0\lib\net45\RazorEngine.dll
  3. #endregion
  4. namespace RazorEngine
  5. {
  6. [Obsolete("Please use the Engine.Razor instance instead.")]
  7. public static class Razor {
  8. public static void Compile(string razorTemplate, string name);
  9. ...
  10. public static ITemplate CreateTemplate(string razorTemplate);
  11. ...
  12. public static ITemplate GetTemplate(string razorTemplate, string name);
  13. ...
  14. public static string Parse(string razorTemplate);
  15. ...
  16. public static ITemplate Resolve(string name);
  17. ...
  18. public static string Run(string name);
  19. ...
  20. public static void SetTemplateService(ITemplateService service);
  21. }
  22. }

缓存

  1. How are templates in RazorEngine cached?
  2. Antaris RazorEngine How to Recompile a template using the same Key?
  3. RazorEngine Memory Usage
  4. RazorEngine IsolatedTemplateService is not preventing growth of number of loaded assemblies
  5. Use external cache provider for RazorEngine
  6. Memcached Caching Provider and Serialization Issue #278

作者说: 无法稍毁缓存

When you change and recompile templates you have a memory leak, because you cannot unload loaded assemblies (which RazorEngine compiles and loads for you in the background).

The only way to really free the memory is to reload the AppDomain or restart the process.

-- http://stackoverflow.com/questions/14369614/razorengine-un-cache-compiled-templates

  • RazorEngine un-cache compiled templates
  • http://github.com/Antaris/RazorEngine/issues/232#issuecomment-128802285
  • Essential Templating - is a set of libraries to render templated objects (like web pages or emails).

某网文代码

《ASP.NET MVC 解析模板生成静态页一 (RazorEngine)》 全文共两部分: 1. 基本的单数据模型模板解析; 2. 面向接口的多数据模型模板解析。该网文仅涉及到 RazorEngine 最基础的 API,未展示 Hello World 之外的功能。以下为第一部分的原始代码 (未改动、仅格式化)。第二部分核心代码与第一部分完全相同,仅增加了 TemplateView 模型解析类中间件、Repository、泛型、面向接口、Spring 依赖注入、反射赋值,所有这些增加的部分都是面向对象与设计模式的半桶水套路,无作用无意义徒增坏味道,跳过。

  1. public class Articles
  2. {
  3. public int Id { get; set; }
  4. public string Title { get; set; }
  5. public string Content { get; set; }
  6. public string Author { get; set; }
  7. public DateTime CreateDate { get; set; }
  8. }
  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  4. <title>@Model.Title</title>
  5. </head>
  6. <body>
  7. <h1>@Model.Title</h1>
  8. <p>作者:@Model.Author - 发布时间:@Model.CreateDate</p>
  9. <p>@Raw(Model.Content)</p>
  10. </body>
  11. </html>
  1. /// <summary>
  2. /// 获取页面的Html代码
  3. /// </summary>
  4. /// <param name="url">模板页面路径</param>
  5. /// <param name="encoding">页面编码</param>
  6. public string GetHtml(string url, System.Text.Encoding encoding)
  7. {
  8. byte[] buf = new WebClient().DownloadData(url);
  9. if(encoding != null){
  10. return encoding.GetString(buf);
  11. }
  12. string html = System.Text.Encoding.UTF8.GetString(buf);
  13. encoding = GetEncoding(html);
  14. if(encoding == null || encoding == System.Text.Encoding.UTF8){
  15. return html;
  16. }
  17. return encoding.GetString(buf);
  18. }
  19. /// <summary>
  20. /// 获取页面的编码
  21. /// </summary>
  22. /// <param name="html">Html源码</param>
  23. public System.Text.Encoding GetEncoding(string html)
  24. {
  25. string pattern = @"(?i)/bcharset=(?<charset>[-a-zA-Z_0-9]+)";
  26. string charset = Regex.Match(html, pattern).Groups["charset"].Value;
  27. try{
  28. return System.Text.Encoding.GetEncoding(charset);
  29. }
  30. catch(ArgumentException){
  31. return null;
  32. }
  33. }
  1. /// <summary>
  2. /// 创建静态文件
  3. /// </summary>
  4. /// <param name="result">Html代码</param>
  5. /// <param name="createpath">生成路径</param>
  6. public bool CreateFileHtmlByTemp(string result, string createpath)
  7. {
  8. if(!string.IsNullOrEmpty(result)) {
  9. if(string.IsNullOrEmpty(createpath)) {
  10. createpath = "/default.html";
  11. }
  12. string filepath = createpath.Substring(createpath.LastIndexOf(@"/"));
  13. createpath = createpath.Substring(0, createpath.LastIndexOf(@"/"));
  14. if (!Directory.Exists(createpath)) {
  15. Directory.CreateDirectory(createpath);
  16. }
  17. createpath = createpath + filepath;
  18. try {
  19. FileStream fs2 = new FileStream(createpath, FileMode.Create);
  20. StreamWriter sw = new StreamWriter(fs2, new System.Text.UTF8Encoding(false));//去除UTF-8 BOM
  21. sw.Write(result);
  22. sw.Close();
  23. fs2.Close();
  24. fs2.Dispose();
  25. return true;
  26. }
  27. catch { return false; }
  28. }
  29. return false;
  30. }
  1. /// <summary>
  2. /// 解析模板生成静态页
  3. /// </summary>
  4. /// <param name="temppath">模板地址</param>
  5. /// <param name="path">静态页地址</param>
  6. /// <param name="t">数据模型</param>
  7. public bool CreateStaticPage(string temppath, string path, Articles t)
  8. {
  9. try {
  10. //获取模板Html
  11. string TemplateContent = GetHtml(temppath, System.Text.Encoding.UTF8);
  12. //解析模板生成静态页Html代码
  13. string result = Razor.Parse(TemplateContent, t);
  14. //创建静态文件
  15. return CreateFileHtmlByTemp(result, path);
  16. }
  17. catch (Exception e) {
  18. throw e;
  19. }
  20. }

安全 - 只可能内部使用、不能让用户定义模板

  1. How dangerous is it to let users specify RazorEngine templates?
  2. RazorEngine for user templates - Security?
  3. ASP.NET Razor templates editable by users - remove @ for security reasons

Resource - Hello World

  1. 利用 RazorEngine 打造简单的泛用代码生成器 - 基于 ExpandoObject
  2. 利用 RazorEngine 更加直观的格式化字符串 - Note: 反射取值的 Regex.Replace() 有实用价值

Resource - Advanced

  1. 第四篇 基于 .NET 搭建热插拔式 Web 框架 (RazorEngine 实现)
  2. 用 Razor 語法寫範本 - RazorEngine 組件介紹
  3. 让 Windows2003 Server NET4.0 Frameworks 可以上使用 RazorEngine 程序集
  4. C# 模板引擎 RazorEngine 3.7 的简单使用
  5. RazorEngine 在非 MVC 下的使用,以及使用自定义模板
  6. .NET MVC Razor 也可以这样玩
  7. 在 ASP.NET WebAPI 中使用 Razor
  8. DIY RazorEngine 的程序集生成方式
  9. 抛弃 NVelocity,来玩玩 Razor - 文件嵌套、@Include()
  10. Razor Engine,实现代码生成器的又一件利器
  11. Razor 模板引擎使用 - 缓存源码?
  12. C# & SQlite 代码生成器 - 非 HTML 模板示例
  13. Razor 模板引擎 - 缓存测试 & 封装
  14. 使用 Razor 模板构建应用注意的细节

base or advanced

    1. 用 Razor 語法寫範本 - RazorEngine 組件介紹
    2. 用 Razor 語法寫範本 - RazorEngine 組件介紹
    3. 让 Windows2003 Server NET4.0 Frameworks 可以上使用 RazorEngine 程序集
    4. RazorEngine - @Html.LabelFor OK, @Html.EditorFor "not implemented exception" on Execute()
    5. Dynamic CSS using Razor Engine
    6. Razor Templating Engine
    7. 代码生成就用 Razor 模板
    8. C# 模板引擎 RazorEngine 3.7 的扩展 — 引入外部文件
    9. C# 模板引擎 RazorEngine 3.7 的扩展 — 引用布局页
    10. 在非网页程序里使用 Razor 模板引擎
    11. ASP.NET MVC 解析模板生成静态页一 (RazorEngine) - 详见本文 "某网文代码" 小节
    12. DIY RazorEngine 的程序集生成方式

Razor - 模板引擎 / 代码生成 - RazorEngine