When writing clean and easy-to-read templates, it's usually good to have structural template tags (e.g. {%for%}, {%if%}) alone on their own line with proper indentation.
When such a template is rendered, the resulting HTML will have blank lines in place of the template tags. The leading blank space used for indentation is also intact.
This template tag strips all empty and all-whitespace lines when rendering the template. Be careful not to apply it when not intended, e.g. when empty lines are wanted inside PRE tags.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import re
from django.utils.functional import allow_lazy
from django.utils.encoding import force_unicode
from django.template import Node, Library
register = Library()
def strip_empty_lines(value):
"""Return the given HTML with empty and all-whitespace lines removed."""
return re.sub(r'\n[ \t]*(?=\n)', '', force_unicode(value))
strip_empty_lines = allow_lazy(strip_empty_lines, unicode)
class GaplessNode(Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
return strip_empty_lines(self.nodelist.render(context).strip())
def gapless(parser, token):
"""
Remove empty and whitespace-only lines. Useful for getting rid of those
empty lines caused by template lines with only template tags and possibly
whitespace.
Example usage::
<p>{% gapless %}
{% if yepp %}
<a href="foo/">Foo</a>
{% endif %}
{% endgapless %}</p>
This example would return this HTML::
<p>
<a href="foo/">Foo</a>
</p>
"""
nodelist = parser.parse(('endgapless',))
parser.delete_first_token()
return GaplessNode(nodelist)
gapless = register.tag(gapless)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
mikko, strange that I didn't find your snippet when I tried to search for one before writing mine.
Actually I think this solution, where blank lines are removed after rendering the lines, is not optimal, because also blank lines inserted on purpose are now lost.
It would be neat if lines with nothing but a template tag (and blank space) were detected and stripped of whitespace and the line feed. I don't have an idea how to implement that though. Probably also tags with non-empty output should retain their indentation.
#
Please login first before commenting.