Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compacting/minifying dynamic html

I am using django templating, and for readability I have html that looks similar to the following:

{% if some_variable %}
    text
{% else %}
    nothing exists here
{% endif %}

{% for item in set %}
    {% if forloop.first %}
...etc...

It converts to the following html at runtime, which includes tons of whitespace and returns:

text

<div>

  <li

        class='some_class

    >

    some text

   </li>

</div>

etc...

Some pages even run to ~3,000 lines of html when viewing the page source.

Is there a tool to compress this html at runtime? What about a tool to remove extra line breaks?

like image 783
David542 Avatar asked Jul 29 '12 22:07

David542


1 Answers

For a bit of background, this is done intentionally, since Django's templating engine currently doesn't care about sanitizing lines that evaluate to blanks after the tags get stripped out and doing so will incur some minor performance penalties in serving the response, since it involves a post-processing step that evaluates the full contents of the rendered template.

Still, if you need a quick solution, I suggest you employ the StripWhitespaceMiddleware response middleware that'll remove spurious whitespaces from textual responses. It's pretty fast and straightforward, employing regular expression matching like the templating engine itself. A more taxing, but powerful alternative would be deploy a response middleware that utilizes an HTML prettifier, if you really care about the poor human beings still reading raw responses.

like image 196
Filip Dupanović Avatar answered Sep 21 '22 04:09

Filip Dupanović