Compacting/minifying dynamic html

Viewed 7596

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?

7 Answers

I recommend using a custom template loader django-spaceless-templates, which strips unnecessary whitespace characters. This approach has two advantages:

  • With the combination with cached template loader, whitespace stripping is done only once during template compilation. On the other hand with {% spaceless %} or middleware approach minification is called every time a template is rendered.
  • Whitespace stripping can be more aggressive - remove spaces between HTML tags, Django tags and variables.
Related