使用新的RazorEngine API进行模板化

时间:2015-02-19 12:14:42

标签: c# razor

前一段时间使用RazorEngine渲染模板非常简单:

string s = RazorEngine.Razor.Parse()

然而,出于某种原因,它的作者改变了他们对API的看法,现在最简单的渲染模板的方法是:

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来渲染模板而不需要缓存,键和其他花哨的东西?所有official examples根本不起作用。

4 个答案:

答案 0 :(得分:68)

好吧,在搜索代码之后,我找到了一些有用的例子(https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Hosts.Console/Program.cs)并发现如果你包含

using RazorEngine.Templating;

在您的课程顶部,您可以使用一些可以帮助您的扩展方法(https://github.com/Antaris/RazorEngine/blob/master/src/source/RazorEngine.Core/Templating/RazorEngineServiceExtensions.cs)。

无痛模板编译:

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);

请注意我正在测试这个,但似乎工作正常。

答案 1 :(得分:6)

以下代码适用于ResolvePathTemplateManager (2017年10月)

var templateManager = new ResolvePathTemplateManager(new[] { rootPath });

var config = new TemplateServiceConfiguration
{
    TemplateManager = templateManager
};

Engine.Razor = RazorEngineService.Create(config);

// ...

var html = Engine.Razor.RunCompile("Test.cshtml", null, model);

来源:在RazorEngineServiceTestFixture.cs中,查找ResolvePathTemplateManager

答案 2 :(得分:0)

在@ turdus-merula的回答基础上,我希望在卸载默认AppDomain时清除临时文件。我在配置中禁用了临时文件锁定,这允许删除临时文件夹。

var config = new TemplateServiceConfiguration
{
    TemplateManager = new ResolvePathTemplateManager(new[] {"EmailTemplates"}),
    DisableTempFileLocking = true
};

Engine.Razor = RazorEngineService.Create(config);

var html = Engine.Razor.RunCompile("Test.cshtml", null, model);

答案 3 :(得分:0)

仅供参考,使用 RazorEngine API 会导致内存泄漏。有一个官方问题报告,编译模板不断生成很难摆脱的临时文件。因此,如果您在生产中使用它,请务必小心。

上次我使用它时,它在每次模板编译时都会向内存增加 +1MB,即使使用缓存模板时也是如此!