检查 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
Check if key exists in a Python dict in Jinja2 templates
提问by Amal Antony
I have a python dictionary:
我有一个 python 字典:
settings = {
"foo" : "baz",
"hello" : "world"
}
This variable settings
is then available in the Jinja2 template.
这个变量settings
随后在 Jinja2 模板中可用。
I want to check if a key myProperty
exists in the settings
dict within my template, and if so take some action:
我想检查我的模板myProperty
中的settings
字典中是否存在一个键,如果存在,请采取一些措施:
{% if settings.hasKey(myProperty) %}
takeSomeAction();
{% endif %}
What is the equivalent of hasKey
that 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 item
does not contain a blabla
key
'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.myProperty
exists, 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 %}