Skip to content

Instantly share code, notes, and snippets.

@jimmydo
Created February 24, 2011 19:29
Show Gist options
  • Save jimmydo/842713 to your computer and use it in GitHub Desktop.
Save jimmydo/842713 to your computer and use it in GitHub Desktop.
collapsespaces is a Django template tag that collapses whitespace characters between tags into one space.
"""collapsespaces is a Django template tag that collapses whitespace characters between tags into one space.
It is based on Django's 'spaceless' template tag (spaceless is different in that it completely removes whitespace between tags).
Why is this important?
Given "<span>5</span> <span>bottles</span>", collapsespaces will preserve the space between the two span elements--spaceless will not.
In a web browser:
"<span>5</span> <span>bottles</span>" renders as "5 bottles"
"<span>5</span><span>bottles</span>" renders as "5bottles"
"""
import re
from django import template
from django.utils.encoding import force_unicode
from django.utils.functional import allow_lazy
register = template.Library()
def collapse_spaces_between_tags(value):
"""Returns the given HTML with whitespace between tags collapsed to one space."""
return re.sub(r'>\s+<', '> <', force_unicode(value))
collapse_spaces_between_tags = allow_lazy(collapse_spaces_between_tags, unicode)
class CollapseSpacesNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
return collapse_spaces_between_tags(self.nodelist.render(context).strip())
def collapsespaces(parser, token):
"""
Collapses whitespace between HTML tags into one space.
Example usage::
{% collapsespaces %}
<p>
<a href="foo/">Foo</a>
</p>
{% endcollapsespaces %}
This example would return this HTML::
<p> <a href="foo/">Foo</a> </p>
Only space between *tags* is collapsed -- not space between tags and text.
In this example, the space around ``Hello`` won't be collapsed::
{% collapsespaces %}
<strong>
Hello
</strong>
{% endcollapsespaces %}
"""
nodelist = parser.parse(('endcollapsespaces',))
parser.delete_first_token()
return CollapseSpacesNode(nodelist)
collapsespaces = register.tag(collapsespaces)
@crispgm
Copy link

crispgm commented Jan 24, 2018

Great work! Thank you so much for sharing this.

@fsboehme
Copy link

fsboehme commented Jun 7, 2018

Thanks for sharing indeed. Still golden after 7 years.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment