I am trying to retrieve the value of a dictionary key and display that on the page in a Django template:
{% for dictkey in keys %}
<p> {{ mydict.dictkey }} </p>
{% endfor %}
(let's say 'keys' and 'mydict' have been passed into the template in the Context)
Django renders the page but without the dictionary contents ("Invalid template variable")
I assume the problem is that it is trying to do mydict['dictkey'] instead of mydict[actual key IN the variable dictkey]? How does one "escape" this behavior?
Thanks!
UPDATE: Based on the answers received, I need to add that I'm actually looking specifically for how to achieve a key lookup inside a for loop. This is more representative of my actual code:
{% for key, value in mydict1.items %}
<p> {{ mydict2.key }} </p>
{% endfor %}
Basically, I have two dictionaries that share the same keys, so I can't do开发者_StackOverflow the items() trick for the second one.
See this answer to a (possibly duplicate) related question.
It creates a custom filter that, when applied to a dictionary with a key as it's argument, does the lookup on the dictionary using the key and returns the result.
Code:
@register.filter
def lookup(d, key):
if key not in d:
return None
return d[key]
Usage:
{% for dictkey in dict1.keys %}
<p> {{ dict2|lookup:dictkey }} </p>
{% endfor %}
Registering the filter is covered in the documentation.
I find it sad that this sort of thing isn't built in.
From http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
The trick is that you need to call dict.items()
to get the (key, value)
pair.
See the docs: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
精彩评论