Login

Parsing Tag decorator

Author:
pgcd
Posted:
May 19, 2010
Language:
Python
Version:
1.2
Tags:
templatetag
Score:
-1 (after 1 ratings)

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

  1. Django Breadcrumbs Snippet by flashingpumpkin 6 years ago
  2. Private Context Decorator by acdha 5 years, 8 months ago
  3. pygments stylize by mgiger 7 years, 9 months ago
  4. A templatetag to insert the output of another view (or local URL) by jamesgpearce 5 years, 10 months ago
  5. Customizable newforms labels with a template tag by exogen 7 years ago

Comments

Please login first before commenting.