umbraco-community/Our-Umbraco-TagHelpers

our-link create an a tag from a Link

Matthew-Wise opened this issue · 0 comments

Tag helper should null check the Link passed.
Add rel nopener if the link is External and target is set to _blank. Although modern browsers now do this by default it will help protect those on older browsers

Don't currently have time to clone down the repo and submit a PR but I do have all the code.

using Microsoft.AspNetCore.Razor.TagHelpers;
using Umbraco.Cms.Core.Models;

[HtmlTargetElement("our-link")]
public class LinkTagHelper : TagHelper
{
    [HtmlAttributeName("Link")]
    public Link? Link { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        if (string.IsNullOrWhiteSpace(Link?.Url))
        {
            output.SuppressOutput();
            return;
        }

        output.TagName = "a";
        var childContent = await output.GetChildContentAsync();
        if (childContent == null)
        {
            output.Content.SetContent(Link.Name);
        }
        output.Attributes.SetAttribute("href", Link.Url);
        if (string.IsNullOrWhiteSpace(Link.Target))
        {
            return;
        }

        output.Attributes.SetAttribute("target", Link.Target);
        if (Link.Target == "_blank" && Link.Type == LinkType.External)
        {
            output.Attributes.SetAttribute("rel", "noopener");
        }
    }