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 - 对对象使用变量键


基础教程推荐
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01