我们为 HtmlHelper 添加了两个扩展:Content
和Block
. Content
允许消费者HtmlStrings
从剃刀代码创建。 Block
尝试允许用户创建带有标题和内容部分的 html 块。我试图理解为什么razorContent
参数不能在 using 块内编译。我想保留 using 块的使用,因为我认为它看起来很干净。有没有办法在不改变第二个参数的情况下进行Block
编译HtmlString
?
剃刀:
@* uses of Html.Content compiles as expected *@
@Html.Content(@<span>foo</span>)
@{
IHtmlString htmlString = Html.Content(@<span>bar</span>);
}
@htmlString
@* "@<span>header</span>" does not compile
*
* expected markup:
* <div class="header">
* <span>header</span>
* </div>
* <div class="content>
* <span>content</span>
* </div>
*@
@using (Html.Block(@<span>header</span>))
{
<span>content</span>
}
扩展:
public static class HtmlHelperExtensions
{
public static IHtmlString Content(this HtmlHelper htmlHelper, Func<object, HelperResult> razorContent)
{
var content = razorContent(null);
return content;
}
public static IDisposable Block(this HtmlHelper htmlHelper, Func<object, HelperResult> razorContent)
{
var content = razorContent(null);
return new MyHtmlBlock(htmlHelper, content);
}
}
我的 HTML 块:
public class MyHtmlBlock : IDisposable
{
private readonly TextWriter _writer;
private readonly TagBuilder _contentTag;
public MyHtmlBlock(HtmlHelper htmlHelper, IHtmlString header)
{
this._writer = htmlHelper.ViewContext.Writer;
var headerTag = new TagBuilder("div");
headerTag.AddCssClass("header");
headerTag.InnerHtml = header.ToHtmlString();
this._contentTag = new TagBuilder("div");
this._contentTag.AddCssClass("content");
this._writer.Write(headerTag);
this._writer.Write(this._contentTag.ToString(TagRenderMode.StartTag));
}
public void Dispose()
{
this._writer.Write(this._contentTag.ToString(TagRenderMode.EndTag));
}
}