Twig:如何在 if 语句中通过键获取数组元素

14

我想在if语句中通过键获取元素的值。

例子:

可行:

{{ example[5] }}

无法工作:

{% if example2 is example[5] %} something ... {% endif %}

抛出异常:

意外的标记"标点符号"值为 "["(应为"语句块结束")

非常感谢

祝一切顺利


2
你想做什么?要比较两个值,使用 ==is 用于一些特殊情况,如 nulldefinedeven - Maerlyn
2个回答

20

不要使用

{% if example2 is example[5] %} something ... {% endif %}

尝试将'is'更改为'=='

{% if example2 == example[5] %} something ... {% endif %}

9
也许你应该使用attribute函数来获取对象或数组的值。这个链接可能会对你有所帮助。

1
我点赞是因为这解决了我的问题,该问题涉及通过另一个数组的值来定位数组中的键。其他人可能正在寻找类似的解决方案并查看此问题。 - Ryan Rentfro

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