a simple tag with context

 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. inclusion tag with template as variable by forgems 5 years, 2 months ago
  2. Private Context Decorator by acdha 4 years, 8 months ago
  3. Mod to allow simple_tag to access context by leaf 5 years, 6 months ago
  4. CatchTag - Catching the content and saving it to a variable by limodou 7 years, 1 month ago
  5. Slightly better media path tag by ubernostrum 6 years, 12 months ago

Comments

(Forgotten your password?)