Opened 19 years ago

Closed 19 years ago

Last modified 17 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

Description

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):
            nodes.append(self)
        nodes.extend(self.nodelist.get_nodes_by_type(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 />
        text
        <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',))
    parser.delete_first_token()
    
    return StripNode(nodelist)

template.register_tag('strip', do_strip)

Change History (5)

comment:1 by Adrian Holovaty, 19 years ago

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

comment:2 by Simon Willison, 19 years ago

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 by Petar Marić <petar.maric@…>, 19 years ago

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 by Adrian Holovaty, 19 years ago

Resolution: fixed
Status: newclosed

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

comment:5 by URL, 18 years ago

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