Login

Template tag: Group variables into list

Author:
Killarny
Posted:
March 13, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

Groups an arbitrary number of variables into a list.

{% group "foo", 2, "bar" as my_list %}

 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
import re
from django import template
register = template.Library()

class GroupNode(template.Node):
    def __init__(self, group_variables, var_name):
        self.group_variables = list()
        for group_variable in group_variables:
            self.group_variables += [template.Variable(group_variable)]
        self.var_name = var_name
    def render(self, context):
        try:
            group = list()
            for variable in self.group_variables:
                group += [variable.resolve(context)]
            context[self.var_name] = group
            return ''
        except template.VariableDoesNotExist:
            return ''

@register.tag
def group(parser, token):
    '''Groups an arbitrary number of variables into a list.
    
    ex: {% group "foo", 2, "bar" as my_list %}
    '''
    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, \
                        "%r tag requires arguments" % token.contents.split()[0]
    m = re.search(r'(.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, \
                                    "%r tag had invalid arguments" % tag_name
    group_string, var_name = m.groups()
    group = [g.strip() for g in group_string.split(',')]
    return GroupNode(group, var_name)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.