Check if key exists in a Python dict in Jinja2 templates

Amal Antony picture Amal Antony · Jan 2, 2015 · Viewed 64.3k times · Source

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?

Answer

tshalif picture tshalif · Jan 17, 2016

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