Login

a simple tag with context

Author:
dsblank
Posted:
December 21, 2009
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

simple_tag is nice, but it would be useful if it had a "as variable" clause at the end. This little bit of code factors out the reusable parts and makes a tag almost as simple as simple_tag. Now you can create tags like the following:

{% some_function 1 2 as variable %}
{% some_function db person %}

To add a new function, just do:

register.tag("new_function", 
             make_tag(new_function))

(I think you have to take the quotes off a string.)

 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
def some_function(db, handle):
    return db.some_method(handle)

class TemplateNode(template.Node):
    def __init__(self, args, var_name, func):
        self.args = map(template.Variable, args)
        self.var_name = var_name
        self.func = func

    def render(self, context):
        value = self.func(*[item.resolve(context) for item in self.args])
        if self.var_name:
            context[self.var_name] = value
            return ''
        else:
            return value

def parse_tokens(tokens):
    items = tokens.contents.split(None)
    # {% tag_name arg1 arg2 arg3 as variable %}
    # {% tag_name arg1 arg2 arg3 %}
    tag_name = items[0]
    if "as" == items[-2]:
        var_name = items[-1]
        args = items[1:-2]
    else:
        var_name = None
        args = items[1:]
    return (tag_name, args, var_name)

def make_tag(func):
    def do_func(parser, tokens):
        tag_name, args, var_name = parse_tokens(tokens)
        return TemplateNode(args, var_name, func)
    return do_func

register.tag("some_function", 
             make_tag(some_function))

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

Please login first before commenting.