Template Tag Render Decorator

 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 4 years, 3 months ago
  2. View decorator providing confirmation dialog by rudyryk 4 years, 2 months ago
  3. DRY template rendering decorator by pfylim 4 years, 2 months ago
  4. Render Decorator by dahool 4 years, 7 months ago
  5. Qucik Render Template Decorator with Contexts by fatiherikli 2 years, 4 months ago

Comments

Romain Hardouin (on March 10, 2010):

Should be a built-in decorator

#

(Forgotten your password?)