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

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.