简体   繁体   中英

get dictionary value by key in django template

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:

  1. Create a folder template_tags in your app folder
  2. Create a file in that folder custom_tags.py
  3. In custom_tags.py have this code from the other answer:
from django.template.defaulttags import register

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)
  1. In settings register your custom tags, add the libraries and leave the rest of the TEMPLATES alone.
TEMPLATES = [
    {
        ...   
        'OPTIONS': {
            'context_processors': [   
            ],

            'libraries': {
            'custom_tags':'YOURAPP.template_tags.custom_tags'
            }
        },
    },
]
  1. In your template:
{% 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

Django template in nested dictionary

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM