compare two variables in jinja2 template

风格不统一 提交于 2020-01-02 01:55:13

问题


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?


回答1:


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 %}



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/12623768/compare-two-variables-in-jinja2-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!