Twig:打印变量名是字符串的变量的值 [英] Twig: Print the value of a variable where the variable name is String

查看:34
本文介绍了Twig:打印变量名是字符串的变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为例如的变量var1 其值为 value1 作为字符串.如何打印变量 var1 的值,其中 var1 以字符串形式获得?

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?

{{ set container = 'var1' }}

变量container 的值是动态的.根据 container 的值,我需要打印它的值;在这种情况下,我需要打印value1".

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'.

我正在寻找这样的东西

{{ attribute(this, container) }}/* <= 这不会,因为 this 没有在 Twig 中定义 */

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

推荐答案

结果我错了.

您可以使用 _context 变量,该变量包含传递给模板的所有变量.

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

试试 {{ dump(_context) }}

相关文档

您可以创建一个函数,通过该上下文和数组键来访问该值.

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];
}

在传递变量title=foo 和传递另一个变量refTitle=title 后,这应该输出foo".

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

{{ attribute(_context, refTitle) }}

这篇关于Twig:打印变量名是字符串的变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆