Anchor If Tag Helper

A simple ASP.NET Core tag helper that either renders as a link or as the given fallback tag.

[HtmlTargetElement("a-if", TagStructure = TagStructure.NormalOrSelfClosing)]
public class AnchorIfTagHelper : TagHelper
{
    public string? Href { get; set; }

    public string? FallbackTag { get; set; } = "div";

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (string.IsNullOrEmpty(Href))
        {
            output.TagName = FallbackTag;
            return;
        }

        output.TagName = "a";
        output.Attributes.SetAttribute("href", Href);
    }
}

If the given href is empty or null, the fallback tag will be used. Otherwise the link will be output. All additional properties are passed to either resulting tag.

Usage

<a-if href="@Model.LinkUrl" class="class" fallback-tag="span">
  To link or not to link... that is the question.
</a-if>

Given @Model.LinkUrl is /some/link, this will output:

<a href="/some/link" class="class">
  To link or not to link... that is the question.
</a>

Given @Model.LinkUrl is an empty string, this will output:

<span class="class"> To link or not to link... that is the question. </span>