Template tag: Group variables into 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. in_group template filter by whiteinge 5 years, 9 months ago
  2. Dynamic Regroup Template Tag by btaylordesign 2 years, 8 months ago
  3. Increment a variable in a Template by sachingupta006 2 years ago
  4. User group template tag by jdriscoll 6 years, 10 months ago
  5. User groups template tag with "else" block support (Allow checking several groups) by br0th3r 1 year, 11 months ago

Comments

(Forgotten your password?)