问题描述
不久前,使用 RazorEngine
渲染模板非常简单:
Some time ago rendering a template using RazorEngine
was as easy as:
string s = RazorEngine.Razor.Parse()
但是,出于某种原因,其作者改变了对 API 的看法,现在呈现模板的最简单方法是:
However, for some reason, its authors changed their minds about the API and now the simplest way to render a template is:
var key = new RazorEngine.Templating.NameOnlyTemplateKey("EmailTemplate", RazorEngine.Templating.ResolveType.Global, null);
RazorEngine.Engine.Razor.AddTemplate(key, new RazorEngine.Templating.LoadedTemplateSource("Ala ma kota"));
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
RazorEngine.Engine.Razor.RunCompile(key, sw);
string s = sb.ToString();
(至少这是我从新 API 中推导出来的.旧 API 被标记为已弃用.)有没有一种方法可以使用新 API 来呈现模板而无需缓存、键和其他花哨的东西?所有官方示例根本不起作用.
(at least this is what I deduced from the new API. Old one is marked as deprecated.) Is there a way to use new API to render a template without caching, keys and other fancy stuff? All official examples simply doesn't work.
推荐答案
好吧,在搜索代码后,我找到了一些有用的示例 (https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Hosts.Console/Program.cs) 并发现如果您包含
Well, after searching the code, I found some useful examples (https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Hosts.Console/Program.cs) and found out that if you include
using RazorEngine.Templating;
在类的顶部,您可以使用一些扩展方法(https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Core/Templating/RazorEngineServiceExtensions.cs) 会帮助你.
at the top of your class, you can use some extension methods (https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Core/Templating/RazorEngineServiceExtensions.cs) that will help you.
无痛模板编译:
Engine.Razor.Compile(templatePath, "templateNameInTheCache", modelType);
模板解析:
Engine.Razor.Run("templateNameInTheCache", modelType, model);
现在您可以同时进行!
string myParsedTemplate = Engine.Razor.RunCompile(templatePath, "templateNameInTheCache", null, model)
这相当于做这个
Engine.Razor.AddTemplate("templateNameInTheCache", TemplateLoader.GetTemplate(templatePath));
Engine.Razor.Compile("templateNameInTheCache", modelType);
string finallyThisIsMyParsedTemplate = Engine.Razor.Run("templateNameInTheCache", modelType);
请注意,我目前正在对此进行测试,但它似乎工作正常.
Please note that I'm currently testing this, but it seems to work fine.
这篇关于使用新的 RazorEngine API 进行模板化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!