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)