How do I access a member in Twig determined by a variable?

Short answer: not directly / natively possible ... yet.

Apparently they added a new function to Twig 1.2 called attribute() which addresses exactly that need.

But as up to this day you can only download Twig 1.1.2; so 1.2 is probably not shipped with SF2 - though I cannot find a version number. (1.2 is available now!)

I tried to solve that with different tricks, but to no avail; 1.2 will fix it.

New in version 1.2: The attribute function was added in Twig 1.2.

attribute can be used to access a “dynamic” attribute of a variable:

{{ attribute(object, method) }}

{{ attribute(object, method,arguments) }}

{{ attribute(array, item) }}


But what you can do though is add a method to your class that takes care of whatever you need. something like that:

php:

class C
{
    public $a = 1;
    public $b = 2;

    public function getValueForKey($k)
    {
        return $this->$k;
    }
}

[ providing an instance of C to the template as 'obj' ]

twig:

{% set x = "a" %}
{{ obj.getValueForKey(x) }}

will output '1'


Use brackets syntax: bldg[key]

Tags:

Php

Twig

Symfony