Jinja2 template variable if None Object sets default value

How to make jijna2's default variable "" if the object is None and not something like this?

{% if p %} {{ p.User['first_name']}} {% else %} NONE {%endif %} 

So, if the p object is None, I want the default values โ€‹โ€‹of p (first_name and last_name) to be "". Basically nvl (p.User [first_name '], "")

Error while receiving: Error: jinja2.exceptions.UndefinedError UndefinedError: "None" does not have the attribute "User"

+116
jinja2
Oct 27 '13 at 2:31 on
source share
9 answers

Use the built-in none 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 }} 
+185
Oct 27 '13 at 8:28
source share
 {{p.User['first_name'] or 'My default string'}} 
+102
Jun 24 '14 at 11:46
source share

According to the documentation you can simply do:

 {{ p|default('', true) }} 

The reason None results in False in a logical context.




Update : As Linda mentioned, it only works for simple data types.

+54
Mar 23 '15 at 19:04
source share

As a complement to the other answers, you can write something else if the variable is None:

 {{ variable or '' }} 
+20
Feb 05 '17 at 19:25
source share

By following this document , you can do it as follows:

 {{ p.User['first_name']|default('NONE') }} 
+7
Jun 03 '14 at 18:15
source share

To avoid throwing an exception while "p" or "p.User" is None, you can use:

 {{ (p and p.User and p.User['first_name']) or "default_value" }} 
+3
25 Oct '17 at 10:14
source share

As another solution (similar to some previous ones):

 {{ ( p is defined and p.User is defined and p.User['first_name'] ) |default("NONE", True) }} 

Note that the last variable (p.User ['first_name']) does not have an if defined test after it.

+1
May 02 '19 at 19:59
source share

I usually define the 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 the template:

 <span>Welcome {{ nvl(person.nick, person.name, 'Anonymous') }}<span> // or <span>Welcome {{ person.nick | nvl(person.name, 'Anonymous') }}<span> 
0
Mar 12 '18 at 13:18
source share

Starting with version 2.8, you can simply use:

 {{ p.User['first_name'] }} 

See https://docs.ansible.com/ansible/latest/porting_guides/porting_guide_2.8.html#jinja-undefined-values

0
Jun 15 '19 at 2:59
source share



All Articles