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?
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 http://jinja.pocoo.org/docs/dev/templates/#list-of-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 %}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With