Templating using new RazorEngine API

前端 未结 3 1863
梦毁少年i
梦毁少年i 2020-12-12 16:15

Some time ago rendering a template using RazorEngine was as easy as:

string s = RazorEngine.Razor.Parse()

However, for some re

相关标签:
3条回答
  • 2020-12-12 16:47

    The following code works for ResolvePathTemplateManager (October, 2017):

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

    Source: in RazorEngineServiceTestFixture.cs, look for ResolvePathTemplateManager.

    0 讨论(0)
  • 2020-12-12 16:53

    Building on @turdus-merula's answer, I wanted the temp files to be cleaned up when the default AppDomain is unloaded. I disabled the temp file locking in the config, which allows the temp folder to be deleted.

    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);
    
    0 讨论(0)
  • 2020-12-12 17:01

    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;
    

    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.

    Painless template compilation :

    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)
    

    Which is the equivalent of doing this

    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.

    0 讨论(0)
提交回复
热议问题