Template tag for stripping blank lines

 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

  1. Updated version of StripWhitespaceMiddleware (v1.1) by sleepycal 1 year, 11 months ago
  2. Skip only specified spaces by axil 1 year, 3 months ago
  3. Soft-wrap long lines by Ubercore 5 years, 1 month ago
  4. easy absolute path for settings.py by pgugged 4 years, 10 months ago
  5. make templates fail loudly in dev by showell 4 years ago

Comments

mikko (on January 31, 2008):

very similar to my snippet: http://www.djangosnippets.org/snippets/523/ :) but i see you use look ahead, i should have thought of that

#

akaihola (on February 25, 2008):

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.

#

(Forgotten your password?)