Twig: type the value of the variable in which the variable name is String

I have a variable with a name, for example. var1which matters value1as a string. How to print the value of a variable var1, where it var1turns out as a string?

Let be

{{ set container = 'var1' }}

The value of the variable containeris dynamic. Depending on the value, containerI need to print its value; in this case I need to type "value1".

I'm looking for something like this

{{ attribute(this, container) }}/ * <= This will not be, as it is thisnot defined in Twig * /

+4
source share
1 answer

Turns out I was wrong.

You can use a variable _contextthat contains all the variables passed to the template.

Try {{ dump(_context) }}

, .

:

public function getAttribute($context, $key)
{
    if (!array_key_exists($key, $context)) {
        return '';
    }

    return $context[$key];
}

title=foo refTitle=title, "foo".

{{ attribute(_context, refTitle) }}
+2

Source: https://habr.com/ru/post/1588975/


All Articles