You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Twig中如何使用attribute()访问嵌套对象的属性?

解决Twig中通过attribute()访问嵌套对象属性的问题

直接使用{{ attribute(item, 'subItem.title') }}无法实现需求,因为Twig的attribute()函数仅支持单个层级的属性/方法调用——它会把'subItem.title'当作完整的属性名去查找,而非解析成嵌套路径。

针对你场景中第二个参数来自Twig变量的情况,可通过以下方法实现嵌套属性访问:

方法:拆分路径后逐层调用attribute()

将嵌套路径按.拆分成数组,循环逐层调用attribute()遍历对象结构:

{# 假设存储嵌套路径的变量为 attr_path,值为 'subItem.title' #}
{% set path_segments = attr_path|split('.') %}
{% set current_obj = item %}

{% for segment in path_segments %}
    {% set current_obj = attribute(current_obj, segment) %}
{% endfor %}

{# 最终 current_obj 即为目标 title 值 #}
{{ current_obj }}

原理说明

Twig访问对象属性时会自动识别对应的getter方法:

  • 调用attribute(item, 'subItem')时,会自动触发item->getSubItem()
  • 后续调用attribute(current_obj, 'title')时,会触发subItem->getTitle()
    完全适配你提供的PHP对象结构中私有属性的访问逻辑。

内容的提问来源于stack exchange,提问作者jedi58

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 06:42:08