鉴于我有两个变量{{ profile }}
,其值为“test”,而{{ element.author }}
的值为“test”。在jinja2中,当我尝试使用if比较它们时,没有任何显示。我按如下方式进行比较:
{% if profile == element.author %}
{{ profile }} and {{ element.author }} are same
{% else %}
{{ profile }} and {{ element.author }} are **not** same
{% endif %}
我得到输出test and test are not same
什么是错的,我怎么比较?
答案 0 :(得分:12)
我遇到同样的问题,两个具有整数值的变量在它们是相同的值时不相等。
有没有办法以任何方式使这项工作。 还尝试使用str()== str()或int()== int()但总是存在未定义的错误。
<强>更新强>
找到解决方案:
只需使用{{ var|string() }}
或{{ var|int() }}
等过滤条件
https://stackoverflow.com/a/19993378/1232796
阅读文档可在此处找到http://jinja.pocoo.org/docs/dev/templates/#list-of-builtin-filters
在你的情况下你想要做
{% if profile|string() == element.author|string() %}
{{ profile }} and {{ element.author }} are same
{% else %}
{{ profile }} and {{ element.author }} are **not** same
{% endif %}
答案 1 :(得分:2)
profile
和element.author
的类型不同,或者不相等。但是,它们确实在转换为字符串时输出相同的值。您需要正确地比较它们或将它们的类型更改为相同。
答案 2 :(得分:1)
您可以使用jinja2提供的众多built in tests之一来检查变量的类型。例如string()
或number()
。我遇到了同样的问题,我意识到这就是类型。
答案 3 :(得分:0)
我建议使用 |lower
过滤器:
{% if profile|lower == element.author|lower %}
这不仅将变量强制转换为相同的字符串类型,还有助于避免因名称可能键入的不同方式而导致的不匹配。