我正在尝试使用 RazorEngine ( http://razorengine.codeplex.com/ ) 生成 HTML 文档。一切正常,但我现在遇到的问题是一些 HTML 正在正确呈现,而我嵌套在其中的 HTML 被呈现为文字 HTML,因此浏览器不是按预期显示表格和 div,而是显示例如
"<table></table><div></div>"
我通过调用以下命令开始此过程:
string completeHTML = RazorEngine.Razor.Parse("InstallationTemplate.cshtml", new { Data = viewModels });
然后将completeHTML
其写入文件。
“InstallationTemplate.cshtml”定义为:
@{
var installationReport = new InstallationReport(Model.Data);
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<div>
<!-- I would expect this to write the rendered HTML
in place of "@installationReport.DigiChannels()" -->
@installationReport.DigiChannels()
</div>
</body>
</html>
其中InstallationReport
和DigiChannels
定义如下:
public static class InstallationReportExtensions
{
public static string DigiChannels(this InstallationReport installationReport)
{
return installationReport.GetDigiChannelsHtml();
}
}
public class InstallationReport
{
public string GetDigiChannelsHtml()
{
// the following renders the template correctly
string renderedHtml = RazorReport.GetHtml("DigiChannels.cshtml", GetDigiChannelData());
return renderedHtml;
}
}
public static string GetHtml(string templateName, object data)
{
var templateString = GetTemplateString(templateName);
return RazorEngine.Razor.Parse(templateString, data);
}
GetDigiChannelsHtml()
运行并返回后renderedHtml
,执行行返回到TemplateBase.cs
方法ITemplate.Run(ExecuteContext context)
中,定义为:
string ITemplate.Run(ExecuteContext context)
{
_context = context;
var builder = new StringBuilder();
using (var writer = new StringWriter(builder))
{
_context.CurrentWriter = writer;
Execute(); // this is where my stuff gets called
_context.CurrentWriter = null;
}
if (Layout != null)
{
// Get the layout template.
var layout = ResolveLayout(Layout);
// Push the current body instance onto the stack for later execution.
var body = new TemplateWriter(tw => tw.Write(builder.ToString()));
context.PushBody(body);
return layout.Run(context);
}
return builder.ToString();
}
当我检查时builder.ToString()
,我可以看到它包含正确的 HTMLInstallationTemplate.cshtml
内容,以及转义的 HTMLDigiChannels.cshtml
内容。例如:
我怎样才能@installationReport.DigiChannels()
包含正确的 HTML 而不是它当前正在执行的转义 HTML?