比较jinja2模板中的两个变量

Posted

技术标签:

【中文标题】比较jinja2模板中的两个变量【英文标题】:compare two variables in jinja2 template 【发布时间】:2012-09-19 09:07:05 【问题描述】:

假设我有两个变量 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 怎么了,我该如何比较?

【问题讨论】:

尝试输入值: [profile, element.author] 意外发布。这个表达式应该代表变量。 【参考方案1】:

我有同样的问题,两个具有整数值的变量在它们是相同的值时不相等。

有没有办法以任何方式使这项工作。 也尝试使用 str() == str() 或 int() == int() 但总是出现未定义的错误。

更新

找到解决方案: 只需使用过滤器,例如 var|string() var|int() https://***.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 %

【讨论】:

【参考方案2】:

profileelement.author 不是同一类型,否则不相等。但是,它们在转换为字符串时确实会输出相同的值。您需要正确比较它们或将它们的类型更改为相同。

【讨论】:

我只是想做一些字符串比较,怎么做? 也许:str(profile) == str(element.author)?如果不知道你的数据和代码的所有类型和其他事情,我不能说。【参考方案3】:

您可以使用 jinja2 提供的众多 built in tests 之一来检查变量的类型。例如string()number()。我有同样的问题,我意识到这是类型。

【讨论】:

【参考方案4】:

我建议使用|lower 过滤器:

% if profile|lower == element.author|lower %

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

【讨论】:

以上是关于比较jinja2模板中的两个变量的主要内容,如果未能解决你的问题,请参考以下文章

django模板语法

Django 模板语言

如何将 Javascript 变量与 Jinja2 变量进行比较

比较 Go 模板中的两个变量

带有缓存加载器的 Jinja2 与 django 模板 - 性能比较如何?

Django 与 Mako Jinja2 模板比较的集成使用:render_to_response。问题?