Jinja2 template variable if None Object set a default value


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 %}
      {%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 tagged with jinja2

~ Asked on 2013-10-27 02:31:01

The Best Answer is


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

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


{{ 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 }}

~ Answered on 2013-10-27 08:28:01


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

~ Answered on 2014-06-24 11:46:59

Most Viewed Questions: