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
相关产品推荐
相关产品推荐

