From: Matthijs Kooijman Date: Fri, 8 Feb 2008 23:01:14 +0000 (+0100) Subject: * Add the gapless template tag from http://www.djangosnippets.org/snippets/569/. X-Git-Url: https://git.stderr.nl/gitweb?a=commitdiff_plain;h=d0e331d60ba2c49680a1f012bb8b81e0ea7c3608;p=matthijs%2Fprojects%2Fxerxes.git * Add the gapless template tag from djangosnippets.org/snippets/569/. --- diff --git a/tools/templatetags/__init__.py b/tools/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tools/templatetags/gapless.py b/tools/templatetags/gapless.py new file mode 100644 index 0000000..9defba5 --- /dev/null +++ b/tools/templatetags/gapless.py @@ -0,0 +1,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:: + +

{% gapless %} + {% if yepp %} + Foo + {% endif %} + {% endgapless %}

+ + This example would return this HTML:: + +

+ Foo +

+ + """ + nodelist = parser.parse(('endgapless',)) + parser.delete_first_token() + return GaplessNode(nodelist) +gapless = register.tag(gapless)