简体   繁体   English

使用变量名称的嵌套字典项目的Django模板语法

[英]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. 在Django模板页面上,我正在尝试访问嵌套字典中的值。

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] . 我想做的是打印项目books[1][2] (如果存在),或者换句话说, 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] 请注意,实际项目可能存在或可能不存在,这就是为什么我在使用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 %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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