ASP.Net Core:一个标签助手输出2个标签

7
使用ASP.Net Core的标签助手,有没有办法将一个标签转换为两个根级别的标签?我知道你可以使用TagHelperOutput.TagName == null完全删除标签,但我想知道如何做相反的操作以输出多个标签。
例如,从以下内容开始:
<canonical href="/testing" />

to:

<link rel="canonical" href="http://www.examples.com/widgets" />
<link rel="next" href="http://www.examples.com/widgets?page=2" />

这是一个示例标签助手,它输出其中一个标签,但不输出另一个标签:
[HtmlTargetElement("canonical")]
public class CanonicalLinkTagHelper : TagHelper
{
    public string Href { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "link";
        output.Attributes.SetAttribute("rel", "canonical");
        output.Attributes.SetAttribute(new TagHelperAttribute("href", new HtmlString(Href)));
    }
}

1
你尝试过移除标签并使用 output.PostContent.AppendHtml 吗? - Neville Nazerane
2个回答

6
根据这份文档,一旦使用TagHelperOutput.TagName == null来删除标记后,您必须能够使用output.PostContent.AppendHtml()添加自定义HTML。

更新

PostContent仅用于添加。要替换整个内容,您需要使用output.Content.SetHtmlContent(


3

TagHelpers 可以输出任意数量的 HTML 内容,只需使用 output.Content 将输出写入即可。以下是一个基本示例:

[HtmlTargetElement("canonical")]
public class CanonicalTagHelper : TagHelper
{
    public string Link1Rel { get; set; }
    public string Link2Rel { get; set; }
    public string Link1Href { get; set; }
    public string Link2Href { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = null;

        outputLink(Link1Rel, Link1Href, output);
        outputLink(Link2Rel, Link2Href, output);            
    }

    private void outputLink(string rel, string href, TagHelperOutput output)
    {
        TagBuilder link = new TagBuilder("link");
        link.Attributes.Add("rel", rel);
        link.Attributes.Add("href", href);
        link.TagRenderMode = TagRenderMode.SelfClosing;

        output.Content.AppendHtml(link);
    }
}

使用方法:

<canonical link1-href="https://link1.com" link1-rel="canocical" link2-href="https://link2.com" link2-rel="next"></canonical>

输出:

<link href="https://link1.com" rel="canocical">
<link href="https://link2.com" rel="next">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接