Check if key exists in a Python dict in Jinja2 templates

PythonDjangoJinja2

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

You can test for key definition this way:

{% if settings.property is defined %}

#...
{% endif %}

Solution 3 - Python

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).

Solution 4 - Python

Actually, in the style of Python, if you do a simple if statement, it will work:

{% if settings.foo %}
Setting Foo: {{ settings.foo }}
{% endif %}
{% if settings.bar %}
Setting Bar: {{ settings.bar }}
{% endif %}
{% if settings.hello %}
Setting Hello: {{ settings.hello }}
{% endif %}

Output:

Setting Foo: baz
Setting Hello: world

Cheers!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmal AntonyView Question on Stackoverflow
Solution 1 - PythontshalifView Answer on Stackoverflow
Solution 2 - Pythonma3ounView Answer on Stackoverflow
Solution 3 - PythonMihai ZamfirView Answer on Stackoverflow
Solution 4 - PythonNFSpeedyView Answer on Stackoverflow