views:

37

answers:

1

I am fairly new to Django and I'm curious if some functionality regarding selecting specific collection values in my templates. What I'd like to do is something like this:

I have an object called content it has a key and a value property and i have a collection of that content object. I'd like to do something like this in my template:

{{ contentCollection.key["item1"].value }}

{{ contentCollection.key["item2"].value }}

rather than having to loop through it to get the key and then grab the value. Is there any way to achieve this?

+2  A: 

If the variable you want to access has a dictionary interface you can use . to access the key values.

From the documentation there is an example:

>>> from django.template import Template, Context
>>> person = {'name': 'Sally', 'age': '43'}
>>> t = Template('{{ person.name }} is {{ person.age }} years old.')
>>> c = Context({'person': person})
>>> t.render(c)
'Sally is 43 years old.

So you should be able to do this in your template (not sure exactly what your data structure looks like though).

{{ contentCollection.key.item1.value }}
{{ contentCollection.key.item2.value }}
Andre Miller
I will definitely try that, the dictionary interface is probably the way to get it to work.
Jeremy B.

related questions