Reputation: 2011
Given I have two variables {{ profile }}
with a value "test" and {{ element.author }}
again with the value "test". In jinja2 when I try to compare them using an if, nothing shows up. I do the comparison as follows:
{% if profile == element.author %}
{{ profile }} and {{ element.author }} are same
{% else %}
{{ profile }} and {{ element.author }} are **not** same
{% endif %}
I get the output test and test are not same
Whats wrong, how can I compare?
Upvotes: 18
Views: 73925
Reputation: 2941
I have the same problem, two variables having an integer value do not equal the same when they are the same value.
Is there any way to make this work in any way. Also tried to use str() == str() or int() == int() but there is always an undefined error.
UPDATE
Found Solution:
Simply use filters such as {{ var|string() }}
or {{ var|int() }}
https://stackoverflow.com/a/19993378/1232796
Reading the doc it can be found here https://jinja.palletsprojects.com/en/3.1.x/templates/#builtin-filters
In your case you would want to do
{% if profile|string() == element.author|string() %}
{{ profile }} and {{ element.author }} are same
{% else %}
{{ profile }} and {{ element.author }} are **not** same
{% endif %}
Upvotes: 26
Reputation: 57
I would suggest using the |lower
filter:
{% if profile|lower == element.author|lower %}
That doesn't only cast the variables to the same string type, but also helps avoid mismatch coming from the different ways names might be typed.
Upvotes: 0
Reputation: 86
You can check the types of the variables using one of the many built in tests that jinja2 has available. For instance string()
or number()
. I had the same problem and I realized that was the types.
Upvotes: 1
Reputation: 16882
profile
and element.author
are not the same type, or otherwise aren't equal. However, they do happen to output the same value when converted to a string. You need to correctly compare them or change their types to be the same.
Upvotes: 2