私はRazorEngine(http://razorengine.codeplex.com/)でHTML文書を生成しようとしています。すべてがで、ほとんどがですが、私は今、HTMLの一部が正しくレンダリングされており、その中に入れ子になっているHTMLが、テーブルを表示するブラウザではなく、リテラルHTMLとしてレンダリングされています。& divs 、それは例えば表示しているHTMLがRazorEngineを使用してリテラル文字列としてレンダリングされています。どうすればこれを防ぐことができますか?
"<table></table><div></div>"
私は、次を呼び出すことによって、このプロセスをキックオフ:
string completeHTML = RazorEngine.Razor.Parse("InstallationTemplate.cshtml", new { Data = viewModels });
completeHTML
は、ファイルに書き込まれます。
"InstallationTemplate.cshtml" は次のように定義される。
次のようにInstallationReport
と
DigiChannels
が定義されている
@{
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>
:
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が含まれるように得ることができますか?
いいえ、私はそれを試していませんでした(知らなかった!)。それは完璧に働いた。ありがとう。あなたの答えを正しいものにする前に、数分待たなければなりません。 – DaveDev
ありがとうございます。はい、Html.Rawと同じことをします(ASP.NET MVCでカミソリを使用する場合) –