Twig converts a string to the object that it represents

imaging that I have an object and that can be called in a branch template, like this:

{{ object1.object2.object3.property3A }}

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

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

My question is: if I have a string,

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

and then it is passed to the branch, how can I get property 3A? In my experience, we can do this in php as follows:

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

But I do not know how to make it work on a branch.

+5
source share
3 answers

I have not tested this, but I think it will be a trick.

{#
    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 %}
+1
source

I donโ€™t think there is a โ€œshortcutโ€ to do this in the branch. If you cannot find an easy way to do this, you can write your own extension that converts STRING_TYPE to VAR_TYPE.

Twig . , .

0

I faced a similar situation. This answer will only work if the object you need is available to the template and you know its name with a string.

In this case, you can access the object using Twig Global Variable _context:

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

And then refer to the methods and variables of the object as usual:

{{ object1.object2.object3.property3A }}
0
source

All Articles