【问题标题】:django template nested dictionary, grab value by keydjango模板嵌套字典,按键抓取值
【发布时间】:2013-11-18 00:13:37
【问题描述】:

在 django 模板中,如果上下文字典中有一个键与另一个字典(嵌套字典)关联,我知道如何迭代它(how to iterate through dictionary in a dictionary in django template?),但我需要通过键找到一个值。

点赞{{ nested_dictionary['key'] }}

但我猜不完全是……

可以使用过滤器,但有更好的方法吗?

【问题讨论】:

  • 过滤器是要走的路:stackoverflow.com/a/8000091/1267329
  • 嗯,好的,谢谢,似乎有空间让这更容易......
  • 您可以随时编写自定义模板标签来执行此操作。不过,通常我更愿意在我的上下文中避免使用这种数据结构。
  • 你试过 {{nested_dictionary.key }} 吗?
  • 对,如果在编写模板时知道密钥,点语法就可以工作。

标签: python html django templates


【解决方案1】:

是的,如果您的视图中有嵌套字典,即:

...
dashTable = {'Key0':{'Key1':{'Key2':{'Key3':5}}}}

context = {'dashTable':dashTable,}
return render(request, 'template.html', context)

然后,您可以在作为上下文传递时调用嵌套字典:

{{ dashTable.Key0.Key1.Key2.Key3 }} 

【讨论】:

    猜你喜欢
    • 2018-11-15
    • 2014-03-04
    • 2021-01-16
    • 2014-12-06
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    相关资源
    最近更新 更多