【问题标题】:ASP.Net Core: Output 2 tags from one tag helperASP.Net Core:从一个标签助手输出 2 个标签
【发布时间】:2019-04-02 22:39:45
【问题描述】:

使用 ASP.Net Core 的 Tag Helpers,有没有办法在根级别将 1 个标签转换为 2 个标签?我知道你可以使用TagHelperOutput.TagName == null 完全删除一个标签,但我想知道如何做相反的事情来输出多个标签。

例如,从:

<canonical href="/testing" />

到:

<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)));
    }
}

【问题讨论】:

  • 您是否尝试过删除标签并使用output.PostContent.AppendHtml

标签: asp.net-core asp.net-core-mvc asp.net-core-2.0 tag-helpers asp.net-core-tag-helpers


【解决方案1】:

根据this documentation,一旦您使用TagHelperOutput.TagName == null 删除标签,您必须能够使用output.PostContent.AppendHtml() 添加自定义HTML

更新

PostContent 只是在后面追加。要替换整个内容,您需要使用output.Content.SetHtmlContent(

【讨论】:

    【解决方案2】:

    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">
    

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2018-10-01
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 2019-03-09
      相关资源
      最近更新 更多