views:

19

answers:

1

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!

A: 

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.

Daniel Roseman
Thanks! I'm glad to have the reassurance. In reading the section on custom filters, it seems like the issue is clarity on making strings HTML safe. It seems to me this would make it impossible so I can see how it would come under the programmer's discretion. Nonetheless, I was thinking about an alternate delimiter for separating dot groups. I can see adding to the tag renderer the ability to add multiple dots to divide the dot string perhaps?thispoll.thechoices..forloop.counter or eventhispoll.thechoices..myselectlist..forloop.counterOh, already ambiguous. Well, back to work.
iJames