- Author:
- nedbatchelder
- Posted:
- February 26, 2008
- Language:
- Python
- Version:
- .96
- Score:
- 2 (after 2 ratings)
Just like {% spaceless %}
, except a single space is preserved between two inline tags (such as <a>
, <em>
, and so on). This lets you use the tag on running text without fear of running two spans of styled text together incorrectly.
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
- Template tag - list punctuation for a list of items by shapiromatron 11 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Had the same problem - ended up using something similar with a single pass regex:
#
Please login first before commenting.