From d0e331d60ba2c49680a1f012bb8b81e0ea7c3608 Mon Sep 17 00:00:00 2001 From: Matthijs Kooijman Date: Sat, 9 Feb 2008 00:01:14 +0100 Subject: [PATCH] * Add the gapless template tag from http://www.djangosnippets.org/snippets/569/. --- tools/templatetags/__init__.py | 0 tools/templatetags/gapless.py | 45 ++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 tools/templatetags/__init__.py create mode 100644 tools/templatetags/gapless.py 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) -- 2.30.2