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.

Raw
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)

2 comments

  1. avatar
    wrote this comment on
    Thanks, this saved my a few hours :)
  2. avatar
    wrote this comment on
    Very useful !!! Thanks for sharing

Reply

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo