Twig - 对对象使用变量键

2022-01-22 00:00:00 php 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) }}

相关文章