* Add the gapless template tag from http://www.djangosnippets.org/snippets/569/.
authorMatthijs Kooijman <matthijs@stdio.flexvps.nl>
Fri, 8 Feb 2008 23:01:14 +0000 (00:01 +0100)
committerMatthijs Kooijman <matthijs@stdio.flexvps.nl>
Fri, 8 Feb 2008 23:01:14 +0000 (00:01 +0100)
tools/templatetags/__init__.py [new file with mode: 0644]
tools/templatetags/gapless.py [new file with mode: 0644]

diff --git a/tools/templatetags/__init__.py b/tools/templatetags/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/tools/templatetags/gapless.py b/tools/templatetags/gapless.py
new file mode 100644 (file)
index 0000000..9defba5
--- /dev/null
@@ -0,0 +1,45 @@
+import re\r
+\r
+from django.utils.functional import allow_lazy\r
+from django.utils.encoding import force_unicode\r
+from django.template import Node, Library\r
+\r
+register = Library()\r
+\r
+def strip_empty_lines(value):\r
+    """Return the given HTML with empty and all-whitespace lines removed."""\r
+    return re.sub(r'\n[ \t]*(?=\n)', '', force_unicode(value))\r
+strip_empty_lines = allow_lazy(strip_empty_lines, unicode)\r
+\r
+class GaplessNode(Node):\r
+    def __init__(self, nodelist):\r
+        self.nodelist = nodelist\r
+\r
+    def render(self, context):\r
+        return strip_empty_lines(self.nodelist.render(context).strip())\r
+\r
+def gapless(parser, token):\r
+    """\r
+    Remove empty and whitespace-only lines.  Useful for getting rid of those\r
+    empty lines caused by template lines with only template tags and possibly\r
+    whitespace.\r
+\r
+    Example usage::\r
+\r
+        <p>{% gapless %}\r
+          {% if yepp %}\r
+            <a href="foo/">Foo</a>\r
+          {% endif %}\r
+        {% endgapless %}</p>\r
+\r
+    This example would return this HTML::\r
+\r
+        <p>\r
+            <a href="foo/">Foo</a>\r
+        </p>\r
+\r
+    """\r
+    nodelist = parser.parse(('endgapless',))\r
+    parser.delete_first_token()\r
+    return GaplessNode(nodelist)\r
+gapless = register.tag(gapless)\r