Login

Template Tag Render Decorator

Author:
stephen_mcd
Posted:
February 24, 2010
Language:
Python
Version:
1.1
Tags:
template tag decorator
Score:
4 (after 4 ratings)

I often find myself needing to create a template tag and all I'm interested in is the token and the render function. This decorator abstracts away the boilerplate code around creating the template node class which is the same each and every time.

 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
A decorator that abstracts away the boilerplate code around creating a template 
node class which is the same each and every time you simply want a templatetag 
with access to the template context and the calling token.

Usage:

@register_render_tag
def my_tag(context, token):
    # parse the token and modify the context
    return "" 

Credits:
--------

Stephen McDonald <steve@jupo.org>

License:
--------

Creative Commons Attribution-Share Alike 3.0 License
http://creativecommons.org/licenses/by-sa/3.0/

When attributing this work, you must maintain the Credits
paragraph above.
"""

from django import template


register = template.Library()


def register_render_tag(renderer):
    """
    Decorator that creates a template tag using the given renderer as the 
    render function for the template tag node - the render function takes two 
    arguments - the template context and the tag token
    """
    def tag(parser, token):
        class TagNode(template.Node):
            def render(self, context):
                return renderer(context, token)
        return TagNode()
    for copy_attr in ("__dict__", "__doc__", "__name__"):
        setattr(tag, copy_attr, getattr(renderer, copy_attr))
    return register.tag(tag)

More like this

  1. Decorate Template Tag (In-Line include and extend with local context) by rhomber 5 years, 6 months ago
  2. View decorator providing confirmation dialog by rudyryk 5 years, 5 months ago
  3. DRY template rendering decorator by pfylim 5 years, 5 months ago
  4. Render Decorator by dahool 5 years, 10 months ago
  5. Qucik Render Template Decorator with Contexts by fatiherikli 3 years, 7 months ago

Comments

romain-hardouin (on March 10, 2010):

Should be a built-in decorator

#

Please login first before commenting.