ASP.Net Core: Output 2 tags from one tag helper
Asked Answered
I

2

7

Using ASP.Net Core's Tag Helpers, is there any way to convert 1 tag into 2 tags at the root level? I know you can remove a tag completely using TagHelperOutput.TagName == null, but I'm wondering how I can do the opposite to output more than one tag.

For example, go from:

<canonical href="/testing" />

to:

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

Here is an example tag helper that outputs one of the tags, but not both:

[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)));
    }
}
Infestation answered 29/10, 2018 at 22:44 Comment(1)
have you tried removing the tag and using output.PostContent.AppendHtml?Contaminate
C
6

According to this documentation, once you have used TagHelperOutput.TagName == null to remove your tags, you must be able to add custom HTML using output.PostContent.AppendHtml()

Update

PostContent is only to append after. To replace entire content you will need to use output.Content.SetHtmlContent(

Contaminate answered 29/10, 2018 at 23:13 Comment(0)
S
3

TagHelpers can output any amount of html you need, just use output.Content to write output. Here is a basic example:

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

Usage:

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

Output:

<link href="https://link1.com" rel="canocical">
<link href="https://link2.com" rel="next">
Sym answered 23/10, 2020 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.