【问题标题】:Access a dictionary element in the Django template with a variable使用变量访问 Django 模板中的字典元素
【发布时间】:2014-10-05 15:53:55
【问题描述】:

情况如下。我们渲染一个视图。

return render(request, 'test.html', {'db_object': db_object, 'dict': dict }

在模板中,我们现在想使用db_object.key 访问字典。在 python 中,你通常会做dict[db_object.key]。在模板中,您可以使用{{ dict.some_key }} 来访问该值。但是下面这种情况你显然不能{{ dict.db_object.key }}

有没有办法做到这一点?

【问题讨论】:

  • 你为什么要传递dict?您可以访问模板中的上下文字典,您只需要执行{{ db_object.key }}..?还是我没有抓住重点?
  • 你不能使用.itemssyntax吗? stackoverflow.com/questions/1275735/…

标签: python django


【解决方案1】:

这在之前已经介绍过了,我找到的最佳解决方案是create a quick custom filter。如果该链接失效,这是代码(我没有编写,但作为参考提供):

@register.filter 
def get_item(dictionary, key): return dictionary.get(key)

在模板中:

{{ dict|get_item:object.key }}

当然,请确保在模板标签上调用 load,以便它们对渲染器可见。

【讨论】:

    猜你喜欢
    • 2014-02-01
    • 1970-01-01
    • 2017-03-09
    • 2014-09-10
    • 2011-01-05
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多