Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)));
    }
}
like image 270
Johnny Oshika Avatar asked Mar 06 '23 04:03

Johnny Oshika


2 Answers

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(

like image 104
Neville Nazerane Avatar answered Mar 18 '23 01:03

Neville Nazerane


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">
like image 44
Esko Avatar answered Mar 18 '23 01:03

Esko