Login

Skip only specified spaces

Author:
axil
Posted:
February 14, 2012
Language:
Python
Version:
1.3
Tags:
spaceless whitespace skip spaces
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. really spaceless (trim spaces at line start) by wolfram 7 years, 4 months ago
  2. Smart Spaceless by btaylordesign 4 years, 1 month ago
  3. Plaintext format (advanced spaceless) by hoverhell 4 years, 1 month ago
  4. smart spaceless by nedbatchelder 7 years, 2 months ago
  5. Spaceless all HTML pages by matrix 2 years, 5 months ago

Comments

Please login first before commenting.