Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

twig convert a string to the object that it represent

Tags:

twig

symfony

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.

like image 407
ferdinandfly Avatar asked Nov 12 '22 10:11

ferdinandfly


1 Answers

I didn't tested this, but i think it schould do the 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 %}
like image 181
DasBaconfist Avatar answered Nov 15 '22 08:11

DasBaconfist