twig将字符串转换为它所代表的对象

fer*_*fly 5 symfony twig

成像我有一个对象,可以在这样的树枝模板中调用:

{{ object1.object2.object3.property3A }}
Run Code Online (Sandbox Code Playgroud)

好吧,它会告诉我如果我们使用php写的内容是:

$object1->getObject2()->getObject3()->getProperty3A();
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果我有一个字符串,

$refString="object1.object2.object3.property3A";
Run Code Online (Sandbox Code Playgroud)

然后它被传递到树枝,我怎么能得到property3A?根据我的经验,我们可以在php中这样做:

$refString="object1->getObject2()->getObject3()->getProperty3A()";
echo $$refString;
Run Code Online (Sandbox Code Playgroud)

但我不知道如何让它在树枝上工作.

小智 1

我没有测试过这个,但我认为它应该可以解决问题。

{#
    recursively reading attributes from an object
    ! object1 must be available !
    theValue is the value of property3A
#}
{% for key in "object1.object2.object3.property3A"|split('.') %}
  {% if not loop.first %}{# skip the 'object1' part #}
    {% set theValue = attribute(theValue|default(object1), key) %}
  {% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)