[Django]-Django Remove all Empty Lines from Template Output

4👍

Try to use django-htmlmin

pip install django-htmlmin

for a single view

Using the decorator
django-htmlmin also provides a decorator, that you can use only on views you want to minify the response:

from htmlmin.decorators import minified_response

@minified_response
def home(request):
    return render_to_response('home.html')

for all project

Using the middleware
All you need to do is add two middlewares to your MIDDLEWARE_CLASSES and enable the HTML_MINIFY setting:

MIDDLEWARE_CLASSES = (
    # other middleware classes
    'htmlmin.middleware.HtmlMinifyMiddleware',
    'htmlmin.middleware.MarkRequestMiddleware',
)

Note that if you’re using Django’s caching middleware, MarkRequestMiddleware should go after FetchFromCacheMiddleware, and HtmlMinifyMiddleware should go after UpdateCacheMiddleware:

MIDDLEWARE_CLASSES = (
    'django.middleware.cache.UpdateCacheMiddleware',
    'htmlmin.middleware.HtmlMinifyMiddleware',
    # other middleware classes
    'django.middleware.cache.FetchFromCacheMiddleware',
    'htmlmin.middleware.MarkRequestMiddleware',
)

You can optionally specify the HTML_MINIFY setting:

HTML_MINIFY = True

The default value for the HTML_MINIFY setting is not DEBUG. You only need to set it to True if you want to minify your HTML code when DEBUG is enabled.

Reference: https://github.com/cobrateam/django-htmlmin

5👍

I didn’t like adding new dependency just for this. I choose a different approach using a custom template tag, lineless just a name.

It removes only empty lines. The lines with spaces or any characters detected by Python strip() function as white space.

Full code

templatetags/custom_filters.py

from django.template import Library,Node

register = Library()

@register.tag
def lineless(parser, token):
    nodelist = parser.parse(('endlineless',))
    parser.delete_first_token()
    return LinelessNode(nodelist)


class LinelessNode(Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        input_str = self.nodelist.render(context)
        output_str = ''
        for line in input_str.splitlines():
            if line.strip():
                output_str = '\n'.join((output_str, line))
        return output_str

Use example

<!DOCTYPE html>{% load custom_filters %}{% lineless %}

...

</html>{% endlineless %}

Or if you want to keep HTML & Blocks syntax correct:

<!DOCTYPE html>{% load custom_filters %}{% lineless %}

...

{% endlineless %}
</html>

Note

  • Readable HTML is not a requirement for production, it just adds more stress on the server. So the best is to activate it only with debug mode.

Leave a comment