Twig - Use variable key for object(Twig - 对对象使用变量键)
问题描述
我正在使用 Twig,但遇到了问题.
I am using Twig and I have a problem.
我想为对象使用变量索引时遇到问题.
I have a problem when I want to use a variable index for an object.
这是我的代码:
{% for label, field in params.fields %}
{{ dump(data.field) }}
{% endfor %}
data 是一个包含 {'email': 'test@test.fr', 'name': 'John'}
的对象.
data is an object containing {'email': 'test@test.fr', 'name': 'John'}
.
Field 是一个字符串数组,包含 ['email', 'name']
Field is an array of string containing ['email', 'name']
我无法动态显示我的对象的值.
I can't show the value my object dynamically.
{{ dump(data.email) }}
有效.
{{ dump(data.email) }}
works.
如何使用动态索引?
推荐答案
在 Twig 语法中,data.field
等于 PHP 中的 $data['field']
.换句话说,Twig 使用 field
作为数组键名,而不是将 field
变量的值作为键名.
In Twig syntax, data.field
is equal to $data['field']
in PHP. In other words, Twig use field
as the array key name instead of taking the value of the field
variable and use it as a key name.
您可以使用 attribute()
功能:
You can use the attribute()
function:
attribute
函数可用于访问动态"属性.变量的属性:
The
attribute
function can be used to access a "dynamic" attribute of a variable:
例子:
{{ dump(attribute(data, field)) }}
{# or simply #}
{{ attribute(data, field) }}
这篇关于Twig - 对对象使用变量键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Twig - 对对象使用变量键
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Laravel 仓库 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01