How can I automatically format Razor output with indentation and line breaks?

I have several Razor pages with a lot of conditional logic, loops, partial representations, etc. It’s easy to preserve the semantic correctness of the output markup, but it’s harder to format it with the correct indentation and line breaks. How can I do this automatically at runtime? Is there a Razor module or extension?

Please do not right-click → Format Selection. To be clear, I want to avoid having to think about formatting when I write Razor pages. I want my Razor markup to be laid out in a way that makes sense to developers (for example, padding inside blocks on the server side), but the rendered HTML should be "muted" for the strange person who clicks "View Source". (I'm not worried about increasing the size of the output, because I use gzip / deflate.)

+3
source share
1 answer

You can use a library, for example TidyNet( http://sourceforge.net/projects/tidynet/ ), implementation ActionFilter:

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    if (filterContext.Result is ViewResult)
    {
        var tidy = new Tidy
            {
                Options =
                    {
                        DocType = DocType,
                        DropFontTags = DropFontTags,
                        LogicalEmphasis = LogicalEmphasis,
                        XmlOut = XmlOut,
                        Xhtml = Xhtml,
                        IndentContent = IndentContent,
                        HideEndTags = HideEndTags,
                        MakeClean = MakeClean,
                        TidyMark = TidyMark,
                    }
                };

        filterContext.RequestContext.HttpContext.Response.Filter =
            new HtmlTidyFilter(filterContext.RequestContext.HttpContext.Response.Filter, tidy);
    }
}

Filter Algorithm:

public override void Write(byte[] buffer, int offset, int count)
{
    var data = new byte[count];
    Buffer.BlockCopy(buffer, offset, data, 0, count);
    string html = Encoding.Default.GetString(buffer);

    using (var input = new MemoryStream())
    {
        using (var output = new MemoryStream())
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(html);
            input.Write(byteArray, 0, byteArray.Length);
            input.Position = 0;
            _tidy.Parse(input, output, new TidyMessageCollection());

            string result = Encoding.UTF8.GetString(output.ToArray());

            byte[] outdata = Encoding.Default.GetBytes(result);
            _stream.Write(outdata, 0, outdata.GetLength(0));
        }
    }
} 

:

[TidyHtml]
public class AnyController : Controller

!;)

: http://blog.aquabirdconsulting.com/2009/10/28/asp-net-mvc-clean-html/

+4

All Articles