简体   繁体   中英

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

I have a variable named eg 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 */

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) }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM