Skip to content

07 - Custom Tag Helpers

Convert this:

1
<email domain="eesti.ee">Support</email>

to

1
<a href="support@eesti.ee">support@eesti.ee</a>

Add first implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
namespace WebApp.TagHelpers;

// target <email> tag
public class EmailTagHelper: TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "a";    // replace original tag
    }
}

Add support in _ViewImports.cshtml

1
2
3
4
@using WebApp
@using WebApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, WebApp

Attribute and Content

Switch over to async version...

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace WebApp.TagHelpers;

// target <email> tag
public class EmailTagHelper : TagHelper
{
    // pascalcase to kebab-case
    public string Domain { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        // replace original tag
        output.TagName = "a"; 

        // get the original tag helper content
        var content = await output.GetChildContentAsync();

        var address = (content.GetContent() + "@" + Domain).ToLower();

        output.Attributes.SetAttribute("href", "mailto:" + address);
        output.Content.SetContent(address);
    }
}

Modify existing taghelpers

Inherit from default AnchorTagHelper, override the Process method and then remove the original Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper in _ViewImports.cshtml file.

1
2
3
4
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers

@addTagHelper *, YourProject

Docs

https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/authoring?view=aspnetcore-8.0