如何将 php 变量传递给 twig 模板

tye*_*yee 5 php templating twig

我发现了很多关于此的讨论,但我似乎无法使其发挥作用。我这样在p​​hp中定义变量

$theme_name = 'layout1';

因此,我尝试了以下方法,通过以下每一项,一次一个,使用 {{ theme.name }} 在我的 CMS 模板中显示“layout1”,但它们都不起作用。带有 $twig 的给出了未定义的变量“twig”。

$theme['name'] = $theme_name;
$app["twig"]->addGlobal("name", $theme_name);
$GLOBALS['theme'] = 'layout1';
$twig->addGlobal('themename', 'layout1');
Run Code Online (Sandbox Code Playgroud)

那么我哪里出错了?

Mic*_*ael 2

Twig 文档涵盖了这一点。

https://twig.symfony.com/doc/2.x/advanced.html

https://twig.symfony.com/doc/2.x/advanced.html#globals

全局变量与任何其他模板变量类似,只是它在所有模板和宏中都可用:

 $twig = new Twig_Environment($loader);
 $twig->addGlobal('text', new Text());
Run Code Online (Sandbox Code Playgroud)

然后,您可以在模板中的任何位置使用文本变量:1

 {{ text.lipsum(40) }}
Run Code Online (Sandbox Code Playgroud)