#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 , 20 years ago
| Summary: | new template tag 'strip' → [patch] new template tag 'strip' |
|---|
comment:2 by , 20 years ago
comment:3 by , 20 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 , 20 years ago
| Resolution: | → fixed |
|---|---|
| Status: | new → closed |
comment:5 by , 19 years ago
| Type: | enhancement |
|---|
Note:
See TracTickets
for help on using tickets.
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.