M S
M S

Reputation: 4093

Twig: Print the value of a variable where the variable name is String

I have a variable named e.g. var1 which has value value1 as string. How can I print the value of variable var1 where var1 is obtained as string?

Let

{{ set container = 'var1' }}

The value of the variable container is dynamic. Depending on the value of container, I need to print its value; in this case, I need to print the 'value1'.

I am looking for something like this

{{ attribute(this, container) }} /* <= This will not since this is not defined in Twig */

Upvotes: 4

Views: 3374

Answers (1)

SamV
SamV

Reputation: 7586

Turns out I was wrong.

You can use the _context variable which contains all variables passed to the template.

Try {{ dump(_context) }}

Relevant Documentation

You can create a function that gets passed this context and the array key to access that value.

This twig function should work fine:

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

    return $context[$key];
}

With the variables being passed title=foo and another variable being passed refTitle=title, this should output "foo".

{{ attribute(_context, refTitle) }}

Upvotes: 2

Related Questions