5

imaging that i have a object and which can be called in a twig template like this:

{{ object1.object2.object3.property3A }}

well, it will show me the content if we use php to write is :

$object1->getObject2()->getObject3()->getProperty3A();

My question is if i have a string ,

$refString="object1.object2.object3.property3A";

and then it is passed to twig, how could i get the property3A? For my experience, we can do this in php like this:

$refString="object1->getObject2()->getObject3()->getProperty3A()";
echo $$refString;

But i do not know how to make it work in twig.

4

3 回答 3

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 %}
于 2013-03-08T11:06:22.220 回答
0

我认为在树枝中没有“捷径”可以做到这一点。如果您找不到简单的方法来执行此操作,您可以编写自己的扩展程序,将 STRING_TYPE 转换为 VAR_TYPE。

Twig internals可能会让你走上正确的轨道。是树枝扩展可行的示例,可能会启发您。

于 2013-03-07T16:42:08.940 回答
0

我遇到了类似的情况。此答案仅在您需要的对象可用于模板并且您通过字符串知道它的名称时才有效。

在这种情况下,您可以使用 Twig 的全局变量访问对象_context

{% set object1 = _context['object1'] %}

然后正常访问对象的方法和变量:

{{ object1.object2.object3.property3A }}
于 2015-06-28T14:00:31.150 回答