Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two variables in jinja2 template

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?

like image 916
user1629366 Avatar asked Sep 27 '12 14:09

user1629366


3 Answers

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 %}
like image 86
tgdn Avatar answered Oct 20 '22 21:10

tgdn


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.

like image 24
mjibson Avatar answered Oct 20 '22 20:10

mjibson


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.

like image 1
mazzi Avatar answered Oct 20 '22 20:10

mazzi