Check If Key Exists in a Python Dict in Jinja2 Templates

Check if key exists in a Python dict in Jinja2 templates

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

Check if key exists in a dict in Jinja2 template on ansible

The answer is simple and it showed on ansible error message. First of all I need to check if var is defined.

{% if interfaces.vlan1 is defined %}
{{ interfaces.vlan1.ip }}
{% else %}
{{ interfaces.vlan2.ip|default("127.0.3.1") }}
{% endif %}

This combination works well.

How to get value from key when sending a dictionary to jinja

You should use square brackets to access the value of a variable key of a dict:

<p> the value is: {{ like_dict[x.id] }} </p>

Jinja2 check if value exists in list of dictionaries

If possible, I would move this logic to the python part of the script before rendering it in Jinja. Because, as stated in the Jinja documentation: "Without a doubt you should try to remove as much logic from templates as possible."

any([person['role'] == 'admin' for person in person_dict_list]) is a lot easier to follow at first glance than the other 2 options.

If that's not an option, I would probably use the first, build in function, because I think it's less prone to errors in edge cases as your own solution, and is about 6x less code.

Django Jinja template display value from dictionary key

Try:

{% for key, value in game_details.items %}
Game: {{ key }}<br/>
Win: {{ value.win }}
{% endfor %}

How to check if given variable exist in jinja2 template?

From the documentation:

defined(value)

Return true if the variable is defined:

{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
See the default() filter for a simple way to set undefined variables.

EDIT:
It seems you want to know if a value passed in to the rendering context. In that case you can use jinja2.meta.find_undeclared_variables, which will return you a list of all variables used in the templates to be evaluated.

Accessing element in dict in jinja2 with a key in context passed by jinja

This appears to work:

>>> import jinja2
>>> from jinja2 import Template
>>>
>>> template = Template("Your repayment options are {{repayment[loan_amount] }}")
>>> template.render(data)
u'Your repayment options are {14: 600, 7: 550}'

jinja2, somewhat like javascript, doesn't really distinguish between item access via like x['foo'] vs x.foo. So, I just used the former method rather than the latter (as inside the {{...}}, everything is already "dereferenced" by jinja).



Related Topics



Leave a reply



Submit