I have a python dictionary:
settings = {
"foo" : "baz",
"hello" : "world"
}
This variable settings
is then available in the Jinja2 template.
I want to check if a key myProperty
exists in the settings
dict within my template, and if so take some action:
{% if settings.hasKey(myProperty) %}
takeSomeAction();
{% endif %}
What is the equivalent of hasKey
that I can use?
Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.
Method 3: Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
You can check if a key exists in a dictionary using the keys() method and IN operator. The keys() method will return a list of keys available in the dictionary and IF , IN statement will check if the passed key is available in the list. If the key exists, it returns True else, it returns False .
Check if Variable is a Dictionary with is Operator We can use the is operator with the result of a type() call with a variable and the dict class. It will output True only if the type() points to the same memory location as the dict class. Otherwise, it will output False .
Like Mihai and karelv have noted, this works:
{% 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
You can test for key definition this way:
{% if settings.property is defined %}
#...
{% endif %}
This works fine doesn'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:
Unable to manage file: Jinja variable 'dict object' has no attribute '[attributeName]'
if you use this approach:
{% if settings.myProperty %}
note:
Will also skip, if settings.myProperty
exists, but is evaluated as False
(e.g. settings.myProperty = 0
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With