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\'
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 '' }}
{{p.User['first_name'] or 'My default string'}}