Django almost spaceless template tag

Django has a {{ spaceless }} tag that's a little too greedy for my taste. Removing all whitespace between HTML tags can actually change what the browser renders, so here's a less greedy variant. However, it removes all whitespace, not just between tags, so if you use the pre tag for example you don't want this.

class AlmostSpacelessNode(Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        return self.remove_whitespace(self.nodelist.render(context).strip())

    def remove_whitespace(self, value):
        value = re.sub(r'\n', ' ', value)
        value = re.sub(r'\s+', ' ', value)
        return value 


@register.tag(name='almostspaceless')
def spaceless(parser, token):
    """   
    Remove all whitespace except for one space from content
    """
    nodelist = parser.parse(('endalmostspaceless',))
    parser.delete_first_token()
    return AlmostSpacelessNode(nodelist)

Published on Feb. 11, 2013 at 3:04 p.m. by Nicolas and tagged spaceless, template, Django. You can follow the discussion with the comment feed for this post. Feeling generous? Donate!

0 comments

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.