RazorEngine布局

min*_*son 46 c# razorengine

我正在使用Razor引擎https://github.com/Antaris/RazorEngine来解析我的电子邮件模板的正文.是否可以定义布局并包含其他.cshtml文件?例如,公共页眉和页脚.

min*_*son 53

在这两个帖子的帮助下,我得到了常见的模板和布局:

RazorEngine字符串布局和部分?

http://blogs.msdn.com/b/hongyes/archive/2012/03/12/using-razor-template-engine-in-web-api-self-host-application.aspx

这是我的解决方案:

解决方案1: 布局

通过设置_Layout使用

@{
    _Layout = "Layout.cshtml";
    ViewBag.Title = Model.Title;
 }
Run Code Online (Sandbox Code Playgroud)

页脚

@section Footer 
{
   @RenderPart("Footer.cshtml")
}
Run Code Online (Sandbox Code Playgroud)

Layout.cshtml

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>
    <head>
    </head>
    <body>
        <div id="content">
            @RenderBody()
        </div> 
        @if (IsSectionDefined("Footer"))
        { 
            <div id="footer">
                @RenderSection("Footer")
            </div>
        }
    </body> 
</html>
Run Code Online (Sandbox Code Playgroud)

TemplateBaseExtensions

使用RenderPart方法扩展TemplateBase

public abstract class TemplateBaseExtensions<T> : TemplateBase<T>
{
    public string RenderPart(string templateName, object model = null)
    {
        string path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Templates", templateName);
        return Razor.Parse(File.ReadAllText(path), model);
    }
}
Run Code Online (Sandbox Code Playgroud)

剃刀配置

将BaseTemplateType设置为TemplateBaseExtensions类

TemplateServiceConfiguration templateConfig = new TemplateServiceConfiguration
{
     BaseTemplateType = typeof(TemplateBaseExtensions<>)
};

Razor.SetTemplateService(new TemplateService(templateConfig));
Run Code Online (Sandbox Code Playgroud)

编辑解决方案2:

如果您使用的是TemplateResolver.不需要RenderPart而是使用@Include

页脚

@section Footer 
{
   @Include("Footer.cshtml")
}
Run Code Online (Sandbox Code Playgroud)

分解器

public class TemplateResolver : ITemplateResolver
{
    public string Resolve(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        string path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Templates", name);
        return File.ReadAllText(path, System.Text.Encoding.Default);
    }
}
Run Code Online (Sandbox Code Playgroud)

配置

TemplateServiceConfiguration templateConfig = new TemplateServiceConfiguration
{
     Resolver = new TemplateResolver()
};
Razor.SetTemplateService(new TemplateService(templateConfig));
Run Code Online (Sandbox Code Playgroud)

由松饼人更新 指定模板并渲染字符串

var templateResolver = Razor.Resolve("Registration.cshtml");
return templateResolver.Run(new ExecuteContext());
Run Code Online (Sandbox Code Playgroud)

此外,我与其他人在此链接一起https://github.com/Antaris/RazorEngine/issues/61曾与使用问题_LayoutLayout工作.

'_Layout'是旧语法.它在未来版本中更新为"布局".

  • 而不是@RendarPart使用@Include("Footer.cshtml",Model),它将使用模板解析器.不需要RendarPart扩展 (3认同)