问题描述
有的时候使用 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来渲染没有缓存,钥匙等花哨的东西模板的方法吗?所有根本不起作用。
推荐答案
好了,搜索代码后,我发现了一些有用的例子(的),并发现,如果包括
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;
在你的类的顶部,你可以使用一些扩展方法(的),这将有助于你
无痛模板编译:
Engine.Razor.Compile(templatePath, "templateNameInTheCache", modelType);
模板解析:
Template Parsing :
Engine.Razor.Run("templateNameInTheCache", modelType, model);
和现在你可以在同一时间一举两得!
And now you can do both at the same time !
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.
这篇关于使用新的API RazorEngine模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!