I have a dictionary like this :
myDict = {key1: item1,
key2: item2}
How can I get item1 by providing key1 in django template and more if I have a nested dict like this:
myDict2 = {key1: {key11: item11,
key12: item12},
key2: {key21: item21,
key22: item22}}
for example how can I get item22
using key22
I know {{ myDict[key1] }}
doesn't work
The short answer is to look at the solution at Django template how to look up a dictionary value with a variable and then apply the filter twice.
{{ myDict2|get_item:"key2"|get_item:"key22"}}
A longer answer (taken heavily from the answer I linked to) is:
from django.template.defaulttags import register
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
],
'libraries': {
'custom_tags':'YOURAPP.template_tags.custom_tags'
}
},
},
]
{% load custom_tags %}
{{ myDict2|get_item:"key2"|get_item:"key22"}}
Typically to iterate through a dict in a template something like this...
{% for key, value in harvest_data.items %}
{{ key }} <br>
{% for key2,value2 in value.items %}
{{ key2 }} <br>
{% for key3, value3 in value2.items %}
{{ key3 }}:{{ value3 }} <br>
{% endfor %}
{% endfor %}
{% endfor %}
With regard to the nested dict rendering in templates I think this is answered here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.