|
| 1 | +using Microsoft.AspNetCore.Razor.TagHelpers; |
| 2 | +using System.Threading.Tasks; |
| 3 | +using Umbraco.Cms.Core.Models; |
| 4 | + |
| 5 | +namespace Our.Umbraco.TagHelpers |
| 6 | +{ |
| 7 | + [HtmlTargetElement("our-link")] |
| 8 | + public class LinkTagHelper : TagHelper |
| 9 | + { |
| 10 | + [HtmlAttributeName("Link")] |
| 11 | + public Link? Link { get; set; } |
| 12 | + |
| 13 | + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) |
| 14 | + { |
| 15 | + // Ensure we have a Url set on the LinkPicker property editor in Umbraco |
| 16 | + if (string.IsNullOrWhiteSpace(Link?.Url)) |
| 17 | + { |
| 18 | + output.SuppressOutput(); |
| 19 | + return; |
| 20 | + } |
| 21 | + |
| 22 | + // If the <our-link /> is self closing |
| 23 | + // Ensure that our <a></a> always has a matching end tag |
| 24 | + output.TagMode = TagMode.StartTagAndEndTag; |
| 25 | + |
| 26 | + output.TagName = "a"; |
| 27 | + var childContent = await output.GetChildContentAsync(); |
| 28 | + |
| 29 | + // If we use the TagHelper <umb-link></umb-link> |
| 30 | + // Without child DOM elements then it will use the Link Name property inside the <a> it generates |
| 31 | + if (childContent.IsEmptyOrWhiteSpace) |
| 32 | + { |
| 33 | + output.Content.SetContent(Link.Name); |
| 34 | + } |
| 35 | + |
| 36 | + // Set the HREF of the <a> |
| 37 | + output.Attributes.SetAttribute("href", Link.Url); |
| 38 | + |
| 39 | + if (string.IsNullOrWhiteSpace(Link.Target)) |
| 40 | + { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + // Set the <a target=""> attribute such as _blank etc... |
| 45 | + output.Attributes.SetAttribute("target", Link.Target); |
| 46 | + |
| 47 | + // If the target is _blank & not an internal picked content node & external |
| 48 | + // Ensure we set the <a rel="noopener"> attribute |
| 49 | + if (Link.Target == "_blank" && Link.Type == LinkType.External) |
| 50 | + { |
| 51 | + output.Attributes.SetAttribute("rel", "noopener"); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments