RazorEngine layouts

后端 未结 4 766
太阳男子
太阳男子 2020-12-12 16:12

I am using the Razor engine https://github.com/Antaris/RazorEngine to parse the body of my email templates. Is it possible to define a layout and include other .cshtml files

4条回答
  •  死守一世寂寞
    2020-12-12 17:03

    The easiest way to implement a layout with RazorEngine is by replacing what your template return in the @RenderBody() of the layout:

     var finalHtml = layout.Replace(@"@RenderBody()", templateHtml);
    

    E.g.:

    Your _Layout.cshtml with the typical @RenderBody()

     
        
        
        
            
    @RenderBody()

    Your RazorEngine template MyTemplate.cshtml

    @using RazorEngine.Templating
    @inherits TemplateBase
    
    

    Hello People

    @Model

    And wherever you call the RazorEngine template:

    var TemplateFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "EmailTemplates");
    var template = File.ReadAllText(Path.Combine(TemplateFolderPath,"MyTemplate.cshtml"));
    var layout = File.ReadAllText(Path.Combine(TemplateFolderPath, "_Layout.cshtml"));
    var templateService = new TemplateService();
    var templateHtml = templateService.Parse(template, myModel, null, null);
    var finalHtml = layout.Replace(@"@RenderBody()", templateHtml);
    

提交回复
热议问题