How to make a variable in jijna2 default to \"\" if object is None instead of doing something like this?
{% if p %}
{{ p.User[\'first_name\'
Following this doc you can do this that way:
{{ p.User['first_name']|default('NONE') }}
To avoid throw a exception while "p" or "p.User" is None, you can use:
{{ (p and p.User and p.User['first_name']) or "default_value" }}
As of Ansible 2.8, you can just use:
{{ p.User['first_name'] }}
See https://docs.ansible.com/ansible/latest/porting_guides/porting_guide_2.8.html#jinja-undefined-values
According to docs you can just do:
{{ p|default('', true) }}
Cause None
casts to False
in boolean context.
Update: As lindes mentioned, it works only for simple data types.
As another solution (kind of similar to some previous ones):
{{ ( p is defined and p.User is defined and p.User['first_name'] ) |default("NONE", True) }}
Note the last variable (p.User['first_name']) does not have the if defined
test after it.
Use the none
builtin function (http://jinja.pocoo.org/docs/templates/#none):
{% if p is not none %}
{{ p.User['first_name'] }}
{% else %}
NONE
{%endif %}
or
{{ p.User['first_name'] if p != None else 'NONE' }}
or if you need an empty string:
{{ p.User['first_name'] if p != None }}