Spooky Custom Template Filter?
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 t开发者_如何学JAVAemplate:
{{ 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!
No, there's no reason not to do this in your own application. I've often done similar filters, and have in fact posted very similar code here in answer to various questions.
It's hard to imagine a way in which providing dictionary lookup could compromise the system. This functionality isn't provided by default within Django because of the original desire to have a restricted template language - it's arguable whether this particular filter should have been provided from the start, but given that it wasn't, it's pretty unlikely to be added now.
精彩评论