Tag Helpers are a cool new feature in ASP.NET Core that let you define custom HTML elements that are processed server-side.
I thought that it would be neat to be able to emit Google Analytics tracking code by writing a single HTML element:
<google-analytics tracking-id="UA-XXXXXXXX-X" />
I was able to accomplish that with the following tag helper:
public class GoogleAnalyticsTagHelper : TagHelper
{
public string TrackingId { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.SuppressOutput();
if (!String.IsNullOrEmpty(TrackingId))
{
var sb = new StringBuilder();
sb.AppendLine($"<script async src=\"https://www.googletagmanager.com/gtag/js?id={TrackingId}\"></script>");
sb.AppendLine("<script>");
sb.AppendLine(" window.dataLayer = window.dataLayer || [];");
sb.AppendLine(" function gtag(){dataLayer.push(arguments);}");
sb.AppendLine(" gtag('js', new Date());");
sb.AppendLine($" gtag('config', '{TrackingId}');");
sb.AppendLine("</script>");
output.Content.SetHtmlContent(sb.ToString());
}
}
}
I hope this blog post helps you out, or gives you inspiration for your own ASP.NET Core tag helpers.