Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC C# Razor Minification

Does anybody have any idea about how to output minified HTML and JavaScript from the Razor engine while keeping custom coding styles?

For example: i want the following code:

<div
    @if (Model.Name != string.Empty)
        @:id="@Model.Name"
>
</div>

To be outputted as <div id="DivId"></div> .

like image 936
hiddenUser Avatar asked Apr 08 '13 11:04

hiddenUser


2 Answers

Look at http://arranmaclean.wordpress.com/2010/08/10/minify-html-with-net-mvc-actionfilter/. there is an example for creating custom action filter witch clear html from WhiteSpaces

Update: The source code quoted from above.

The stream class for removing "blanks"

using System;
using System.IO;
using System.Text;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace RemoveWhiteSpace.ActionFilters
{
    public class WhiteSpaceFilter : Stream
    {

        private Stream _shrink;
        private Func<string, string> _filter;

        public WhiteSpaceFilter(Stream shrink, Func<string, string> filter)
        {
            _shrink = shrink;
            _filter = filter;
        }


        public override bool CanRead { get { return true; } }
        public override bool CanSeek { get { return true; } }
        public override bool CanWrite { get { return true; } }
        public override void Flush() { _shrink.Flush(); }
        public override long Length { get { return 0; } }
        public override long Position { get; set; }
        public override int Read(byte[] buffer, int offset, int count)
        {
            return _shrink.Read(buffer, offset, count);
        }
        public override long Seek(long offset, SeekOrigin origin)
        {
            return _shrink.Seek(offset, origin);
        }
        public override void SetLength(long value)
        {
            _shrink.SetLength(value);
        }
        public override void Close()
        {
            _shrink.Close();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            // capture the data and convert to string 
            byte[] data = new byte[count];
            Buffer.BlockCopy(buffer, offset, data, 0, count);
            string s = Encoding.Default.GetString(buffer);

            // filter the string
            s = _filter(s);

            // write the data to stream 
            byte[] outdata = Encoding.Default.GetBytes(s);
            _shrink.Write(outdata, 0, outdata.GetLength(0));
        }
    }
}

The ActionFilter class:

public class WhitespaceFilterAttribute : ActionFilterAttribute
{

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        var request = filterContext.HttpContext.Request;
        var response = filterContext.HttpContext.Response;

        response.Filter = new WhiteSpaceFilter(response.Filter, s =>
                {
                    s = Regex.Replace(s, @"\s+", " ");
                    s = Regex.Replace(s, @"\s*\n\s*", "\n");
                    s = Regex.Replace(s, @"\s*\>\s*\<\s*", "><");
                    s = Regex.Replace(s, @"<!--(.*?)-->", "");   //Remove comments

                    // single-line doctype must be preserved 
                    var firstEndBracketPosition = s.IndexOf(">");
                    if (firstEndBracketPosition >= 0)
                    {
                        s = s.Remove(firstEndBracketPosition, 1);
                        s = s.Insert(firstEndBracketPosition, ">");
                    }
                    return s;
                });

        }

}

And in the end the usage of above:

[HandleError]
[WhitespaceFilter]
public class HomeController : Controller
{
     ...
}
like image 98
Piotr Stapp Avatar answered Nov 15 '22 22:11

Piotr Stapp


I don't think that there is any way to achieve that. To avoid the tag soup I usually prefer writing custom helpers:

@using(Html.MyDiv(Model.Name))
{
    ... put the contents of the div here
}

and here's how the custom helper might look like:

public static class HtmlExtensions
{
    private class Div : IDisposable
    {
        private readonly ViewContext context;
        private bool disposed;

        public Div(ViewContext context)
        {
            this.context = context;
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                this.disposed = true;
                context.Writer.Write("</div>");
            }
        }
    }

    public static IDisposable MyDiv(this HtmlHelper html, string id)
    {
        var div = new TagBuilder("div");
        if (!string.IsNullOrEmpty(id))
        {
            div.GenerateId(id);
        }
        html.ViewContext.Writer.Write(div.ToString(TagRenderMode.StartTag));
        return new Div(html.ViewContext);            
    }
}

Alternatively you could also do a tag soup:

<[email protected](Model.Name != string.Empty ? string.Format(" id=\"{0}\"", Html.AttributeEncode(Model.Name)) : string.Empty)>
</div>
like image 32
Darin Dimitrov Avatar answered Nov 15 '22 22:11

Darin Dimitrov