检查 Jinja2 模板中的 Python 字典中是否存在密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27740153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:12:08  来源:igfitidea点击:

Check if key exists in a Python dict in Jinja2 templates

pythondjangojinja2

提问by Amal Antony

I have a python dictionary:

我有一个 python 字典:

settings = {
   "foo" : "baz",
   "hello" : "world"
}

This variable settingsis then available in the Jinja2 template.

这个变量settings随后在 Jinja2 模板中可用。

I want to check if a key myPropertyexists in the settingsdict within my template, and if so take some action:

我想检查我的模板myProperty中的settings字典中是否存在一个键,如果存在,请采取一些措施:

{% if settings.hasKey(myProperty) %}
   takeSomeAction();
{% endif %}

What is the equivalent of hasKeythat I can use?

hasKey我可以使用的等价物是什么?

采纳答案by tshalif

Like Mihai and karelv have noted, this works:

就像 Mihai 和 karelv 所指出的,这是有效的:

{% if 'blabla' in item %}
  ...
{% endif %}

I get a 'dict object' has no attribute 'blabla'if I use {% if item.blabla %}and itemdoes not contain a blablakey

'dict object' has no attribute 'blabla'如果我使用{% if item.blabla %}并且item不包含blabla密钥,我会得到一个

回答by Mihai Zamfir

This works finedoesn't work in cases involving dictionaries. In those cases, please see the answer by tshalif. Otherwise, with SaltStack (for example), you will get this error:

作品罚款不涉及字典的情况下工作。在这些情况下,请参阅 tshalif 的回答。否则,使用 SaltStack(例如),您将收到此错误:

Unable to manage file: Jinja variable 'dict object' has no attribute '[attributeName]'

Unable to manage file: Jinja variable 'dict object' has no attribute '[attributeName]'

if you use this approach:

如果您使用这种方法:

{% if settings.myProperty %}

{% if settings.myProperty %}

note:
Will also skip, if settings.myPropertyexists, but is evaluated as False(e.g. settings.myProperty = 0).

注意
如果settings.myProperty存在,也会跳过,但被评估为False(例如settings.myProperty = 0)。

回答by ma3oun

You can test for key definition this way:

您可以通过以下方式测试密钥定义:

{% if settings.property is defined %}

#...
{% endif %}