我正在尝试使用RazorEngine(http://razorengine.codeplex.com/)生成HTML文档。一切都主要工作,但我现在遇到的问题是一些HTML正在被正确呈现,我嵌套在其中的HTML被呈现为文字HTML,所以而不是浏览器显示桌子和桌子按预期划分,它显示例如
"<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()
时,我可以看到它包含InstallationTemplate.cshtml
内容的正确HTML,并为DigiChannels.cshtml
内容转义了HTML。例如:
如何让@installationReport.DigiChannels()
包含正确的HTML而不是目前正在进行的转义HTML?
答案 0 :(得分:19)
你试过了吗?
@Raw(installationReport.DigiChannels())
编辑:我可以按照以下方式使用它(MVC3)
@Html.Raw(installationReport.DigiChannels())
答案 1 :(得分:5)