我正在使用 Razor 引擎 https://github.com/Antaris/RazorEngine解析我的电子邮件模板的正文。是否可以定义布局并包含其他 .cshtml 文件?例如常见的页眉和页脚。
最佳答案
在这两篇文章的帮助下,我得到了通用模板和布局:
RazorEngine string layouts and sections?
这是我的解决方案:
解决方案 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/