Twig 使用变量访问数组值

标签 twig

{% set key = 'something' %}

我的 array 有关键的东西,我可以访问 array['something'],但是当我尝试在关键中使用变量时:

array[key]

我收到数组键不存在的错误。所以问题是如何使用变量访问数组键。

最佳答案

您可以使用 attribute功能:

{{ attribute(array, key) }}

来自文档:

addition, the defined test can check for the existence of a dynamic attribute:

{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}

希望对你有帮助

关于Twig 使用变量访问数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39829656/

相关文章:

css - 如何使用 Twig 渲染包含 }} 序列的 CSS 模板

php - 像素集成到 Opencart 3

javascript - 带 Twig 的模板 Nordemailer

php - 如何在 TWIG 函数中获取当前模板名称

symfony - 如何在 Twig 模板中渲染 Controller 返回的图像

javascript - Jquery 函数 submit() 在 ajax 成功函数中不起作用

css - 无法完全滚动浏览菜单

symfony - 如何在我的选择选项中禁用编码 "&"

javascript - 在 Symfony2 中使用 Twig 作为 JavaScript 的 Assetic 过滤器

twig - Symfony 和 PhpStorm twig 没有给我任何关于 twig 函数的建议