Login

Template Tag Render Decorator

Author:
stephen_mcd
Posted:
February 24, 2010
Language:
Python
Version:
1.1
Score:
5 (after 5 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 <[email protected]>

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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

romain-hardouin (on March 10, 2010):

Should be a built-in decorator

#

Please login first before commenting.