Login

Tag that parses args and kwargs

Author:
fivethreeo
Posted:
October 5, 2008
Language:
Python
Version:
1.0
Score:
1 (after 1 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. 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.