answers = { 'a':1, 'b':2, 'c':3 }
and in my template I have
{% for answer in answers.keys %}
{{answer}} = {{answers.answer}}<br/>
{% endfor %}
I would expect this to print
a = 1
b = 2
c = 3
but I get
a =
b =
c =
Am I wrong that the dot notation is supposed to do dictionary lookup
or is there some other way to do this?
(I'm using m-r 2746.)
Thanks,
Todd
The problem you are encountering is that Django is looking for the
literal key 'answer' in your dictionary. It does not do indirection in
the way you are expecting (look at the value of 'answer' and then use
that value to do the lookup.
To achieve what you are after, you can do this:
{% for answer in answers.items %}
{{ answer.0 }} = {{ answer.1 }}<br/>
{% endfor %}
This will give you the answer in arbitrary order, however. If you want
to sort things, you can use a slightly undocumented side-effect of the
dictsort filter and apply it to the list in the loop head (the
undocumented fact is that "|dictsort" works on lists like this, not just
dictionaries):
{% for answer in answers.items|dictsort:"0" %}
{{ answer.0 }} = {{ answer.1 }}<br/>
{% endfor %}
This will sort on the "key" in the dictionary -- the first argument in
each tuple in the list.
Cheers,
Malcolm
answers['answer']
answers.answer
answers.answer()
you want:
answers[answer]
but the template engine doesn't know that you mean answer to be a
variable rather than a literal.
--Ned.
--
Ned Batchelder, http://nedbatchelder.com