在jinja2模板中比较两个变量

16

假设我有两个变量{{ profile }}{{ 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。出了什么问题,我应该如何进行比较?


尝试输入一个值:{{ [profile,element.author] }} - defuz
不小心发布了。这个表达式应该采用变量的表示形式。 - defuz
4个回答

25
我有同样的问题,两个具有整数值的变量在它们的值相同时并不相等。
有没有办法让这个工作起来呢? 我也尝试过使用str() == str()或int() == int(),但总是出现未定义的错误。
更新:
找到解决方案: 只需使用过滤器,如{{ var|string() }}或{{ var|int() }} 链接:https://dev59.com/sGkw5IYBdhLWcg3wfKnZ#19993378 阅读文档可以在这里找到:https://jinja.palletsprojects.com/en/3.1.x/templates/#builtin-filters 在你的情况下,你想要做的是:
{% if profile|string() == element.author|string() %}
{{ profile }} and {{ element.author }} are same
{% else %}
{{ profile }} and {{ element.author }} are **not** same
{% endif %}

1
以防万一,此答案中提供的文档新链接为https://jinja.palletsprojects.com/en/3.1.x/templates/#builtin-filters,截至2023年7月。 - Gary Strivin'

2

profileelement.author 不是同一类型,或者它们不相等。然而,当它们转换为字符串时,它们确实输出相同的值。你需要正确比较它们或更改它们的类型使它们相同。


1
我只是想进行一些字符串比较,怎么做? - user1629366
也许:str(profile) == str(element.author)?不知道您的数据和代码的所有类型和其他信息,我无法确定。 - mjibson

1
您可以使用 jinja2 提供的多种 内置测试 之一来检查变量的类型。例如 string()number()。我曾经遇到过同样的问题,后来发现是变量类型的问题。

0
我建议使用 |lower 过滤器:
{% if profile|lower == element.author|lower %}

这不仅将变量转换为相同的字符串类型,还有助于避免由名称可能以不同方式键入而导致的不匹配。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接