Jinja2 template variable if None Object set a default value

ID : 20195

viewed : 22

Tags : jinja2jinja2

Top 5 Answer for Jinja2 template variable if None Object set a default value

vote vote

96

Use the none test (not to be confused with Python's None object!):

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

or:

{{ p.User['first_name'] if p is not none else 'NONE' }} 

or if you need an empty string:

{{ p.User['first_name'] if p is not none }} 
vote vote

87

{{p.User['first_name'] or 'My default string'}} 
vote vote

76

According to docs you can just do:

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

Cause None casts to False in a boolean context.

vote vote

66

As addition to other answers, one can write something else if variable is None like this:

{{ variable or '' }} 
vote vote

52

Following this doc you can do this that way:

{{ p.User['first_name']|default('NONE') }} 

Top 3 video Explaining Jinja2 template variable if None Object set a default value

Related QUESTION?