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
- LazyPrimaryKeyRelatedField by LLyaudet 6 days, 4 hours ago
- CacheInDictManager by LLyaudet 6 days, 11 hours ago
- MYSQL Full Text Expression by Bidaya0 1 week ago
- Custom model manager chaining (Python 3 re-write) by Spotted1270 1 week, 6 days ago
- Django Standard API Response Middleware for DRF for modern frontend easy usage by Denactive 4 weeks, 1 day ago
Comments
Please login first before commenting.