Hi Folks,
I was having trouble trying to iterate on a template on two dimensions at the same time.
The basic situation is explained here:
http://www.djangobook.com/en/2.0/chapter04/ ( in the apples, bananas indices example )
>>> from django.template import Template, Context
>>> t = Template('Item 2 is {{ items.2 }}.')
>>> c = Context({'items': ['apples', 'bananas', 'carrots']})
>>> t.render(c)
u'Item 2 is carrots.'
If I wanted to iterate from 1 to 3 on this with the variable "fruitstep", I cannot do it in a template:
{{ items.fruitstep }} fails and considering long dot chains, this concept would lead to massive iteration requirements on the template. But I couldn't find a standard way of doing it and I'm not sure it's good template practice.
So, I created a Template filter:
@register.filter
def key2value(collection,key):
try:
return collection[unicode(key)] # It seems that my collection
# keys are in unicode...
except:
return ""
This seems like an extremely powerful filter. It started off being a very specific tag, but I couldn't think of a reason not to make it completely generic.
I'm wondering if there is a standard way to do this and I've reinvented the wheel, or if this code could do something that can compromise the system.
Thanks!