A simple decorator to register a template.Node object as a tag, without the need to write the usual "token.split_contents()
yatta yatta blatta blatta" function.
The decorator should be called with the name of the tag, and an optional required
named argument in case your tag requires a minimum number of arguments.
Please note that all the arguments in the templatetag call will be passed to the node (except the templatetag name and the for
and as
keywords) in the order given.
Suggestions etc are very welcome, of course =)
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 | def parsingTag(node, name, required=0):
r"""
Decorator to replace the standard tag mini-parser.
Will pass all the parameters to the node, in the order given, after filtering out "for" and "as".
Sample tag:
@parsingTag("a_tag")
class ANode(template.Node):
def __init__(self, someval, retval):
self.someval=someval
self.retval=retval
def render(self, context):
context[self.retval]=self.someval
print self.someval
return ''
Sample template usage:
{% a_tag for "example" as retval %}
"""
#@ register.tag(name=name)
def do_parsing(parser, token):
args=token.split_contents()
args=filter(lambda x: x not in ['for', 'as'], args)
if required<len(args):
return node(*args[1:])
else:
raise template.TemplateSyntaxError, "Tag %s requires at least %s arguments"%(args[0], required)
register.tag(name, do_parsing)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.