c# - RazorEngine 布局

标签 c# razorengine

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

最佳答案

在这两篇文章的帮助下,我得到了通用模板和布局:

RazorEngine string layouts and sections?

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

页脚

@section Footer 
{
   @RenderPart("Footer.cshtml")
}

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>

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

Razor 配置

将 BaseTemplateType 设置为您的 TemplateBaseExtensions 类

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

Razor.SetTemplateService(new TemplateService(templateConfig));

编辑 方案二:

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

页脚

@section Footer 
{
   @Include("Footer.cshtml")
}

解析器

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

配置

TemplateServiceConfiguration templateConfig = new TemplateServiceConfiguration
{
     Resolver = new TemplateResolver()
};
Razor.SetTemplateService(new TemplateService(templateConfig));

The Muffin Man 更新 指定模板并渲染字符串

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

我和其他人一起在这个链接 https://github.com/Antaris/RazorEngine/issues/61使用 _Layout 时遇到问题,而 Layout 有效。

'_Layout' 是旧语法。它在未来的版本中更新为“布局”。

关于c# - RazorEngine 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11414194/

相关文章:

c# - IEnumerable 模型中的多个 DropDownList

c# - 带有 RazorEngine 的 Linq 命名空间

c# - 从联系页面返回索引页面

c# - 使用 'inherits' 关键字时不允许使用 'model' 关键字

c# - 在 Linq-To-Entities 中是否有替代 DateTime.Ticks 或 DateTime.TimeOfDay 的方法?

c# - 为什么这个从接口(interface)到类的转换失败了?

c# - 完成 TPL 数据流链

c# - 没有主体的虚拟方法

asp.net-mvc - 剑道小部件在 Razor 中有两层深,内联标记 block 不能嵌套

c# - ASP.Net Core 2.1 注册自定义 ClaimsPrincipal