Twig - 对对象使用变量键 [英] Twig - Use variable key for object

查看:19
本文介绍了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 - 对对象使用变量键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆