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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.