Login

Tag that parses args and kwargs

Author:
fivethreeo
Posted:
October 5, 2008
Language:
Python
Version:
1.0
Tags:
template tag args kwargs
Score:
0 (after 0 ratings)

A tag that parses args ang kwargs like the url tag.

{% get_with_args_and_kwargs somevar,"sometext",kwarg1=someothervar %}
 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from django.template import Library, Node, TemplateSyntaxError

register = Library()

def parse_args_kwargs_and_as_var(parser, bits):

    args = []
    kwargs = {}
    as_var = None
    
    bits = iter(bits)
    for bit in bits:
        if bit == 'as':
            as_var = bits.next()
            break
        else:
            for arg in bit.split(","):
                if '=' in arg:
                    k, v = arg.split('=', 1)
                    k = k.strip()
                    kwargs[k] = parser.compile_filter(v)
                elif arg:
                    args.append(parser.compile_filter(arg))
    return args, kwargs, as_var

def get_args_and_kwargs(args, kwargs, context):
    out_args = [arg.resolve(context) for arg in args]
    out_kwargs = dict([(smart_str(k,'ascii'), v.resolve(context)) for k, v in kwargs.items()])
    return out_args, out_kwargs
    
class SomeObject(object):
    
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

class GetWithArgsAndKwargs(Node):
    
    def __init__(self, args, kwargs, as_var):
        self.args = args
        self.kwargs = kwargs
        self.as_var = as_var
            
    def render(self, context):
        
        args, kwargs = get_args_and_kwargs(self.args, self.kwargs, context)
        
        # call something with the args or kwargs here 
        some_object = SomeObject(*args, **kwargs)
        
        context[self.as_var] = some_object
        
        return ''
        
def get_with_args_and_kwargs(parser, token):

    bits = token.contents.split(' ')
    if len(bits) < 1:
        raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0])
        
    if len(bits) > 1:
        args, kwargs, as_var = parse_args_kwargs_and_as_var(parser, bits[1:])
        
    return GetWithArgsAndKwargs(args, kwargs, as_var)
    
register.tag(get_with_args_and_kwargs)

More like this

  1. Parse custom template tag's args or kwargs by t_rybik 4 years, 7 months ago
  2. CallTag - Just like include, but can pass parameters to it by limodou 8 years, 2 months ago
  3. Other approach of making middleware (by decorators) by diverman 4 years, 1 month ago
  4. DateTimeField with microseconds by tobias 6 years, 2 months ago
  5. Owner required decorator by polarbear 6 years, 9 months ago

Comments

Please login first before commenting.