Search code examples
jinja2

jinja2 string comparison when one value is null?


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!


Solution

  • 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!