smart spaceless

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@register.tag
def smartspaceless(parser, token):
    nodelist = parser.parse(('endsmartspaceless',))
    parser.delete_first_token()
    return SmartSpacelessNode(nodelist)

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

    def render(self, context):
        s = self.nodelist.render(context).strip()
        inline_tags = 'a|b|i|u|em|strong|sup|sub|tt|font|small|big'
        inlines_with_spaces = r'</(%s)>\s+<(%s)\b' % (inline_tags, inline_tags)
        s = re.sub(inlines_with_spaces, r'</\1>&#preservespace;<\2', s)
        s = re.sub(r'>\s+<', '><', s)
        s = s.replace('&#preservespace;', ' ')
        return s

More like this

  1. really spaceless (trim spaces at line start) by wolfram 6 years, 3 months ago
  2. Twitter template tags and filters by moxypark 3 years, 8 months ago
  3. Smart Spaceless by btaylordesign 3 years ago
  4. Analogue template filter to removetags that also removes the content of the tag by piquadrat 3 years, 5 months ago
  5. Plaintext format (advanced spaceless) by hoverhell 3 years ago

Comments

johnboxall (on October 6, 2010):

Had the same problem - ended up using something similar with a single pass regex:

import re

spaces_re = re.compile(r'>\s{2,}<')

def sane_spaces(value):
    return spaces_re.sub('> <', force_unicode(value))
sane_spaces = allow_lazy(sane_spaces, unicode)

#

(Forgotten your password?)