将TagHelpers嵌套在ASP.NET Core MVC中

Muh*_*eed 9 asp.net razor asp.net-core-mvc tag-helpers asp.net-core

ASP.NET Core TagHelper文档提供了以下示例:

public class WebsiteContext
{
    public Version Version { get; set; }
    public int CopyrightYear { get; set; }
    public bool Approved { get; set; }
    public int TagsToShow { get; set; }
}

[TargetElement("website-information")]
public class WebsiteInformationTagHelper : TagHelper
{
    public WebsiteContext Info { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "section";
        output.Content.SetContent(
            $@"<ul><li><strong>Version:</strong> {Info.Version}</li>
            <li><strong>Copyright Year:</strong> {Info.CopyrightYear}</li>
            <li><strong>Approved:</strong> {Info.Approved}</li>
            <li><strong>Number of tags to show:</strong> {Info.TagsToShow}</li></ul>");
        output.TagMode = TagMode.StartTagAndEndTag;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后可以在Razor .cshtml中使用它,如下所示:

<website-information info="new WebsiteContext {
    Version = new Version(1, 3),
    CopyrightYear = 1790,
    Approved = true,
    TagsToShow = 131 }"/>
Run Code Online (Sandbox Code Playgroud)

这将生成以下HTML:

<section>
    <ul>
        <li><strong>Version:</strong> 1.3</li>
        <li><strong>Copyright Year:</strong> 1790</li>
        <li><strong>Approved:</strong> true</li>
        <li><strong>Number of tags to show:</strong> 131 </li>
    </ul>
</section>
Run Code Online (Sandbox Code Playgroud)

这是非常难看的标记助手语法.有没有办法嵌套另一个标记帮助器并获得完全的智能,以便网站信息的唯一允许子项可以是上下文?见下面的例子:

<website-information>
    <context version="1.3" copyright="1790" approved tags-to-show="131"/>
</website-information>
Run Code Online (Sandbox Code Playgroud)

在我的用例中,website-information元素已经有很多属性,我想添加一个或多个单独的嵌套元素.

UPDATE

我在ASP.NET GitHub页面上提出了这个建议,为TagHelpers实现了这个功能.

Dan*_*.G. 16

您当然可以嵌套标记帮助程序,但可能其他选项(如视图组件,部分视图或显示模板)可能更适合OP描述的方案.

这可能是一个非常简单的标记助手:

[HtmlTargetElement("child-tag", ParentTag="parent-tag")]
public class ChildTagHelper : TagHelper
{
    public string Message { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        // Create parent div
        output.TagName = "span";
        output.Content.SetContent(Message);
        output.TagMode = TagMode.StartTagAndEndTag;     
    }
}
Run Code Online (Sandbox Code Playgroud)

这也可能是另一个简单的标记助手:

[HtmlTargetElement("parent-tag")]
[RestrictChildren("child-tag")]
public class ParentTagHelper: TagHelper
{
    public string Title { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {            
        output.TagName = "div";

        // Add some specific parent helper html
        var header = new TagBuilder("h1");
        header.Attributes.Add("class", "parent-title");
        header.InnerHtml.Append(this.Title);
        output.PreContent.SetContent(header);

        // Set the inner contents of this helper(Will process any nested tag helpers or any other piece of razor code)
        output.Content.SetContent(await output.GetChildContentAsync());            
    }
}
Run Code Online (Sandbox Code Playgroud)

在剃须刀视图中,您可以编写以下内容:

<parent-tag title="My Title">
    <child-tag message="This is the nested tag helper" />
</parent-tag>
Run Code Online (Sandbox Code Playgroud)

哪个将呈现为:

<div>
    <h1 class="parent-title">My Title</h1>
    <span>This is the nested tag helper</span>
</div>
Run Code Online (Sandbox Code Playgroud)

您可以选择强制标记帮助程序以特定方式嵌套:

  • 使用[RestrictChildren("child-tag", "another-tag")]父标签帮助限制所允许嵌套的标签助手
  • ParentTag在声明子标记帮助程序时强制使用嵌套在特定父标记内的标记时,请使用该参数[HtmlTargetElement("child-tag", ParentTag = "parent-tag")]


小智 6

我在网上没有找到多重嵌套标签助手的好例子;所以,我在MultiplyNestedTagHelpers GitHub Repository创建了一个。

当使用多个级别的嵌套标签助手时,为每个可以包含子标签的标签设置一个“上下文”类很重要。子标签使用这些上下文类来编写它们的输出。上下文类是一个常规的 POCO 类,每个子标签都有一个属性。属性可能是字符串,但我使用 StringBuilder。例如,

public class MyTableContext{
    public StringBuilder TableHeaderBuilder { get; set; } = new StringBuilder();
    public StringBuilder TableBodyBuilder { get; set; } = new StringBuilder();
}
public class MyTableHeaderContext {
    public StringBuilder RowBuilder { get; set; } = new StringBuilder();
}
//...etc.
Run Code Online (Sandbox Code Playgroud)

在每个父标签的 Process 方法中,您需要实例化父标签的关联上下文类,并将这个新对象添加到 TagHelperContext 对象的 Items 集合中。例如:

    //create context for this tag helper
    var tableContext = new MyTableContext();
    context.Items.Add(typeof(MyTableContext), tableContext);
Run Code Online (Sandbox Code Playgroud)

在子标记的 Process 方法中,您可以像这样写入父级的注册上下文对象:

    //get reference to parent context, and append content to the relevant builder
    var tableContext = context.Items[typeof(MyTableContext)] as MyTableContext;
    tableContext.TableHeaderBuilder.Append(sb.ToString());

    //suppress output (for any tag with a parent tag)
    output.SuppressOutput();
Run Code Online (Sandbox Code Playgroud)

回到父标签的 Process 方法,您会收到子标签的输出,如下所示:

    //you can use a StringBuilder to build output 
    //    or just write to output.Content.AppendHtml() for top-level tags
    var sb = new StringBuilder();
    //...      

    //retrieve the child output and append it to sb
    await output.GetChildContentAsync();
    sb.Append(tableHeaderContext.RowBuilder.ToString());
    //...

    //write to TagHelperOutput for top-level tags      
    output.Content.AppendHtml(sb.ToString());
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这正是我一直在寻找的东西。 (2认同)