Opened 14 years ago

Closed 13 years ago

Last modified 12 years ago

#276 closed (fixed)

[patch] new template tag 'strip'

Reported by: mr_little Owned by: Adrian Holovaty
Component: Template system Version:
Severity: normal Keywords: template tag strip
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Useful extension to templatetags (idea copied from smarty)
Used when you build colored diagramms by images

If you add it to a default set it will be nice ;)

strip_re = re.compile(">\s*")
class StripNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist
    def __iter__(self):
        for node in self.nodelist:
            yield node
    def get_nodes_by_type(self, nodetype):
        nodes = []
        if isinstance(self, nodetype):
        return nodes
    def render(self, context):
        content = self.nodelist.render(context)
        content = strip_re.sub('>', content)
        return content

def do_strip(parser, token):
    Strips spaces and newlines after html tags '>\s*' --> '>'
    {% strip %}
        <img />
        <img />
    {% endstrip %}
    Will be:
        <img />text <img />
    bits = token.contents.split()
    if len(bits) > 2:
        raise template.TemplateSyntaxError, "'%s' tag don't takes arguments" % bits[0]
    nodelist = parser.parse(('endstrip',))
    return StripNode(nodelist)

template.register_tag('strip', do_strip)

Change History (5)

comment:1 Changed 14 years ago by Adrian Holovaty

Summary: new template tag 'strip' [patch] new template tag 'strip'

comment:2 Changed 14 years ago by Simon Willison

I like the functionality, but I'm not too keen on the name. To my mind, "strip" means "remove leading and trailing whitespace from this string" - this tag does quite a bit more than that.

How about calling it "normalize"? That's the term XML parsers use for this kind of thing. Alternatively, a name with "whitespace" in it would be good, if a little verbose.

comment:3 Changed 14 years ago by Petar Marić <petar.maric@…>

Is this one going to be in the trunk any time soon?

As for the tags name I personaly recommend "remove-whitespace" and an alias (would be nice) called (gasp!) "strip".

comment:4 Changed 13 years ago by Adrian Holovaty

Resolution: fixed
Status: newclosed

(In [1967]) Fixed #1067 and #276 -- Added a {% spaceless %} tag, available in all templates

comment:5 Changed 13 years ago by URL

Type: enhancement
Note: See TracTickets for help on using tickets.
Back to Top