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)));
}
}
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(
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With