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']}}
{% else %}
NONE
{%endif %}
So if object p is None I want to default the values of p (first_name and last_name) to "". Basically
nvl(p.User[first_name'], "")
Error receiving:
Error: jinja2.exceptions.UndefinedError
UndefinedError: 'None' has no attribute 'User'
This question is related to
jinja2
Following this doc you can do this that way:
{{ p.User['first_name']|default('NONE') }}
I usually define an nvl
function, and put it in globals
and filters
.
def nvl(*args):
for item in args:
if item is not None:
return item
return None
app.jinja_env.globals['nvl'] = nvl
app.jinja_env.filters['nvl'] = nvl
Usage in a template:
<span>Welcome {{ nvl(person.nick, person.name, 'Anonymous') }}<span>
// or
<span>Welcome {{ person.nick | nvl(person.name, 'Anonymous') }}<span>
As addition to other answers, one can write something else if variable is None like this:
{{ variable or '' }}
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
You can simply add "default none" to your variable as the form below mentioned:
{{ your_var | default('NONE', boolean=true) }}
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.
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" }}
{{p.User['first_name'] or 'My default string'}}
Source: Stackoverflow.com