Django has a useful {% spaceless %}
tag that strips extra whitespace from HTML.
My templates are producing a lot of whitespace and it\'s too much of a pain
I had this problem when I wanted to print inline-block level elements without separation between them (for example to render a fluid grid of blocks), but I wanted a clean looking markup.
jinja2-htmlcompress strips whitespace between HTML tags, but also between jinja tags and variables. That is not ideal because it forces you to use workarounds such as {{ ' ' }}
or hardcoded html entities such as
.
coffin's spaceless tag looks like the ideal solution, but it adds a dependency (django) and a lot of unnecessary functionality.
If you only want to use Django's spaceless tags, you can use the following code which I've adapted from coffin:
jinja_extensions.py
# -*- coding: utf-8 -*-
from jinja2 import nodes
from jinja2.ext import Extension
import re
class SpacelessExtension(Extension):
"""
Removes whitespace between HTML tags at compile time, including tab and newline characters.
It does not remove whitespace between jinja2 tags or variables. Neither does it remove whitespace between tags
and their text content.
Adapted from coffin:
https://github.com/coffin/coffin/blob/master/coffin/template/defaulttags.py
"""
tags = set(['spaceless'])
def parse(self, parser):
lineno = parser.stream.next().lineno
body = parser.parse_statements(['name:endspaceless'], drop_needle=True)
return nodes.CallBlock(
self.call_method('_strip_spaces', [], [], None, None),
[], [], body,
).set_lineno(lineno)
def _strip_spaces(self, caller=None):
return re.sub(r'>\s+<', '><', caller().strip())
Wherever you define your jinja2 environment
extensions=['path.to.jinja_extensions.SpacelessExtension']
Usage example
{% spaceless %} {# We remove whitespace between these inline-block tags without affecting the markup #}
Feature 1
Content
Feature 2
Content
Feature 3
Content
Feature 4
Content
Feature 5
Content, second line on desktop
{% endspaceless %}
Result with spaceless
Result without spaceless (notice that the invisible whitespace has moved the fourth block to the next line)