Jinja2 template variable if None Object set a default value

mcd picture mcd · Oct 27, 2013 · Viewed 196.1k times · Source

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'

Answer

tbicr picture tbicr · Oct 27, 2013

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