Skip to content

Instantly share code, notes, and snippets.

@Bartmax
Created November 5, 2015 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bartmax/b00ccd6e570efa473747 to your computer and use it in GitHub Desktop.
Save Bartmax/b00ccd6e570efa473747 to your computer and use it in GitHub Desktop.
using Microsoft.AspNet.Razor.TagHelpers;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting;
using System;
namespace ProjectName.TagHelpers
{
[HtmlTargetElement("html", Attributes = MinifyAttributeName)]
public class HtmlMinifierTagHelper : TagHelper
{
private readonly HtmlContentCompressor HtmlMinifier;
private readonly string CurrentEnvironmentName;
private static readonly char[] NameSeparator = new[] { ',' };
private const string MinifyAttributeName = "minify";
/// <summary>
/// A comma separated list of environment names in which the content should be rendered.
/// </summary>
/// <remarks>
/// The specified environment names are compared case insensitively to the current value of
/// <see cref="IHostingEnvironment.EnvironmentName"/>.
/// </remarks>
[HtmlAttributeName(MinifyAttributeName)]
public string EnvironmentNames { get; set; }
public HtmlMinifierTagHelper(HtmlContentCompressor htmlMinifier, IHostingEnvironment env)
{
HtmlMinifier = htmlMinifier;
CurrentEnvironmentName = env.EnvironmentName?.Trim();
}
public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var environments = EnvironmentNames?.Split(NameSeparator, StringSplitOptions.RemoveEmptyEntries)
.Where(name => !string.IsNullOrWhiteSpace(name));
if (environments == null || environments.Contains(CurrentEnvironmentName, StringComparer.OrdinalIgnoreCase))
{
// Matching environment name found, minify
var childContent = await output.GetChildContentAsync();
var minifyContent = HtmlMinifier.Compress(childContent.GetContent());
output.Content.SetHtmlContent(minifyContent);
}
TagHelperAttribute attr;
if (output.Attributes.TryGetAttribute("minify", out attr))
{
output.Attributes.Remove(attr);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment