Created
November 5, 2015 00:35
-
-
Save Bartmax/b00ccd6e570efa473747 to your computer and use it in GitHub Desktop.
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 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