Smart Spaceless

 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
This example assumes you have placed this code into a file called "template_additions.py"
and placed that folder into a "templatetags" folder inside a module.
It can live wherever you need.

Example folder structure:
/lib/
    /__init__.py
    /templatetags/
        /__init__.py
        /template_additions.py
"""

from django.conf import settings
from django import template
from django.utils.html import strip_spaces_between_tags

register = template.Library()

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

    def render(self, context):
        content = self.nodelist.render(context)
        return content if settings.DEBUG else strip_spaces_between_tags(content.strip())

@register.tag
def smart_spaceless(parser, token):
    """
    Removes whitespace between HTML tags, including tab and newline characters,
    but only if settings.DEBUG = False

    Example usage:
        {% load template_additions %}
        {% smart_spaceless %}
            <p>
                <a href="foo/">Foo</a>
            </p>
        {% end_smart_spaceless %}

    This example would return this HTML:

        <p><a href="foo/">Foo</a></p>

    Only space between *tags* is normalized -- not space between tags and text.
    In this example, the space around ``Hello`` won't be stripped:

        {% smart_spaceless %}
            <strong>
                Hello
            </strong>
        {% end_smart_spaceless %}
    """
    nodelist = parser.parse(('end_smart_spaceless',))
    parser.delete_first_token()
    return SmartSpacelessNode(nodelist)

More like this

  1. really spaceless (trim spaces at line start) by wolfram 6 years, 3 months ago
  2. Spaceless all HTML pages by matrix 1 year, 3 months ago
  3. smart spaceless by nedbatchelder 6 years, 1 month ago
  4. Skip only specified spaces by axil 2 years, 2 months ago
  5. Plaintext format (advanced spaceless) by hoverhell 3 years ago

Comments

(Forgotten your password?)