Last active
April 17, 2016 04:39
-
-
Save jwmcpeak/c84eaf776f11faf57d77d84becc023b7 to your computer and use it in GitHub Desktop.
A quick Tag Helper for adding an external link icon to external links.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Microsoft.AspNet.Razor.TagHelpers; | |
using Microsoft.AspNet.Http; | |
namespace McPeak.TagHelpers { | |
[HtmlTargetElement("a", Attributes = "href")] | |
public class ExternalLinkTagHelper : TagHelper { | |
private readonly string _hostName; | |
private readonly string[] _schemesToIgnore = new[] { | |
"mailto", | |
"javascript" | |
}; | |
public ExternalLinkTagHelper(IHttpContextAccessor httpContext) { | |
_hostName = httpContext.HttpContext.Request.Host.ToString(); | |
} | |
public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { | |
var href = context.AllAttributes["href"].Value.ToString(); | |
Uri uri; | |
if (NotAbsoluteHref(href, out uri) || | |
ShouldFilterScheme(uri) || | |
IsInternalLink(uri)) { | |
return; | |
} | |
var existingContent = await output.GetChildContentAsync(); | |
output.Content.Append(existingContent); | |
// assuming font awesome | |
output.Content.AppendHtml(@" <i class=""fa fa-external-link"" aria-hidden=""true""></i>"); | |
} | |
private bool NotAbsoluteHref(string href, out Uri uri) { | |
return !Uri.TryCreate(href, UriKind.Absolute, out uri); | |
} | |
private bool ShouldFilterScheme(Uri uri) { | |
return _schemesToIgnore.Contains(uri.Scheme.ToLower()); | |
} | |
private bool IsInternalLink(Uri uri) { | |
return uri.Host == _hostName; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment