Reputation: 1994
Jinja2 template code:
{% if u.user_name == u.user_email %}
{{ u.user_email }}
{% else %}
{{ u.user_name }}<br />
{{ u.user_email }}
{% endif %}
Usually the data source sets the user_name field to user_email if there is no separate name. However, sometimes there is nothing defined for the user_name field at all.
The problem is that in the Jinja2 code above, if the user_name field is undefined / null, the test above evaluates to false and both lines get spit out — one of which is blank.
I'm not sure how to properly write this test syntax. I've read the documentation and have tried approaches like Convert integer to string Jinja and compare two variables in jinja2 template. I guess I have a problem with data types, I'm just not sure how to write this syntax so that it works.
Any help is appreciated!
Upvotes: 5
Views: 21821
Reputation: 21
There are these options for u.username
:
u.user_name
is not definedu.user_name
is None
u.user_name
is an empty stringu.user_name
is a non-empty string{% if u.user_name is not defined or u.user_name == None or u.user_name == '' or u.user_name == u.user_email %}
{{ u.user_email }}
{% else %}
{{ u.user_name }} <br />
{{ u.user_email }}
{% endif %}
But a shorter solution is to use default
filter:
{% if u.user_name | default(u.user_email, true) == u.user_email %}
{{ u.user_email }}
{% else %}
{{ u.user_name }} <br />
{{ u.user_email }}
{% endif %}
If u.user_name
is not defined, default
filter returns its first argument (a default value), otherwise it returns u.user_name
.
It is important to set the second argument of default
to true
. In that case default
returns its first argument (the default value) for u.user_name
defined as None
or as an empty string.
Upvotes: 2
Reputation: 4598
You want is None... try this
{% if (u.user_name == None or u.user_name == '') and u.user_name == u.user_email %}
{{ u.user_email }}
{% else %}
{{ u.user_name }}<br />
{{ u.user_email }}
{% endif %}
Hope this helps!
Upvotes: 8