Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Tag Helper - replace the html tag

I've created a Tag Helper that reads a txt file that contains meta tags and writes the content to the page. But the original tag doesn't change after Process is executed. I want to completely replace the original tag with the content of the txt file.

Tag Helper

[HtmlTargetElement("LC_meta")]
public class MetaTagHelper : TagHelper
{
    private IHostingEnvironment _env;

    [HtmlAttributeName("filename")]
    public string Filename { get; set; } = "default.txt";

    public MetaTagHelper(IHostingEnvironment env)
    {
        _env = env;
    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
       output.Content.SetContent(System.IO.File.ReadAllText(System.IO.Path.Combine(_env.WebRootPath, "META", this.Filename)));
    }
}

and this is the original tag's:

<LC_meta />
<LC_meta filename="sample.txt" />

I'm kinda stuck, so many thanks in advance!

like image 227
SteinTheRuler Avatar asked Apr 18 '17 03:04

SteinTheRuler


1 Answers

If you want to omit the tag, then just set the tagname to NULL and write the text:

public override void Process(TagHelperContext context, TagHelperOutput output)
{
    output.TagName = null;
    output.TagMode = TagMode.StartTagAndEndTag;
    output.PostContent.SetContent("<h1>this gets HTML encoded<h1>");
    output.PostContent.SetHtmlContent("<h1>Hello World</h1>");
}

or if you want to change the tag name, set the tagname to something else:

public override void Process(TagHelperContext context, TagHelperOutput output)
{
    output.TagName = "pre";
    output.TagMode = TagMode.StartTagAndEndTag;
    output.PostContent.SetContent("<h1>this gets HTML encoded<h1>");
    output.PostContent.SetHtmlContent("<h1>Hello World</h1>");
}

Also, be sure your cshtml file contains

@addTagHelper *, ASSEMBLY_NAME_OF_CLASS_WITH_TAGHELPER

at the beginning (before layout), e.g.

@addTagHelper *, BlueMine
like image 82
Stefan Steiger Avatar answered Sep 17 '22 23:09

Stefan Steiger