Login

Skip only specified spaces

Author:
axil
Posted:
February 14, 2012
Language:
Python
Version:
1.3
Score:
1 (after 1 ratings)

Similar to {% spaceless %}, but only removes spaces followed by a special marker (&nosp;).

Helps keeping proper indentation:

{% skipspaces %}
    Lots of coffee
    {% if from_brazil %}
        from Brazil
    {% else %}
        from Columbia
    {% endif %}
    {% if tea %}&nosp;, some tea{% endif %}
    and a cake.
{% endskipspaces %}

Otherwise you'd have to write it in one looong line or get used to living with spaces before commas :)

NB the marker itself is stripped from rendered html as well.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import re
from django import template
from django.utils.encoding import force_unicode
from django.utils.functional import allow_lazy

register = template.Library()

def skip_spaces(value):
    "Return the given HTML with specified spaces removed."
    return re.sub(r'\s*&nosp;', '', force_unicode(value)) # Remove all whitespace before &nosp; along with &nosp; itself
skip_spaces = allow_lazy(skip_spaces, unicode)

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

    def render(self, context):
        return skip_spaces(self.nodelist.render(context).strip())

@register.tag
def skipspaces(parser, token):
    """like spaceless, but removes spaces only where specified by &nosp; entities"""
    nodelist = parser.parse(('endskipspaces',))
    parser.delete_first_token()
    return SkipSpacesNode(nodelist)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.