This tag is meant to override the current implementation of '{% spaceless %}' tag and remove spaces at the beginning of a line too. I.e. a template like this:
<div>
<div>useless space up front</div>
</div>
will become this
<div>
<div>useless space up front</div>
</div>
All the other behaviour of spaceless stays the same!
Put this in your app/name/templatetags/tags.py And if you want it to override the default "spaceless"-tag to the following
from django.template import add_to_builtins
add_to_builtins('app.name.templatetags.tags')
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class SpacelessNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
return strip_spaces_between_tags(self.nodelist.render(context).strip())
@register.tag
def spaceless(parser, token):
"""like spaceless, just removes the spaces at the beginning of a line too"""
nodelist = parser.parse(('endspaceless',))
parser.delete_first_token()
return SpacelessNode(nodelist)
def strip_spaces_between_tags(value):
"Return the given HTML with spaces between tags removed."
value = re.sub(r'\n\s+', '\n', force_unicode(value)) # Replace all leading spaces at the beginning of a line!
return re.sub(r'>\s+<', '><', force_unicode(value))
strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, unicode)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks 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, 6 months ago
Comments
Note that this will erase all leading spaces in pre-Tags too.
#
You need to add in some import statements at the top there...
#
Please login first before commenting.