简体   繁体   中英

Django template syntax for nested dictionary item using variable names

On a Django template page, I'm trying to access the value inside a nested dictionary.

books = 
 { 
   1: { 1: 'Alice', 2: 'Bob', 3: 'Marta' }, 
   2: { 1: 'Alice', 3: 'Marta' }, 
   3: { 1: 'Alice', 2: 'Bob' }, 
 }

Somewhere on my page, I have these two variables

info.id = 1
detail.id = 2

What I want to do is print (if it exists) the item books[1][2] , or in other words books[info.id][detail.id] . I ran into trouble because I couldn't access this nested variable. This got solved here . However, the solution proposed was to access nested dictionary items using the dot notation. But the problem is that this doesn't seem to work when using variables. Using that logic, I would do:

{{ books.info.id.detail.id }}

But this doesn't yield any result. How should I approach the situation when using variables to access the items in a dictionary? Do note that the actual item may or may not exist, which is why I run into trouble using books[info.id][detail.id]

You can't do this in the template directly. You'll need to use a custom template tag . This would work:

@register.simple_tag
def nested_get(dct, key1, key2):
    return dct.get(key1, {}).get(key2)

Now you can use it in the template:

{% load my_tags_library %}
{% nested_get books item.id detail.id %}

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