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

问题描述 投票:2回答:3

我已经就此发现了不少讨论,但我似乎无法使其发挥作用。我用这种方式在php中定义变量

$theme_name = 'layout1';

所以我尝试了以下方法,使用{{theme.name}}使用{{theme.name}}在我的CMS模板中显示'layout1',每次一个,但是没有一个工作。带有$ twig的那个给了未定义的变量'twig'。

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

那我哪里错了?

php twig templating
3个回答
1
投票

您还可以将整个数组添加到Twig:

$theme_name = 'layout1';
$somevar = 'blah';

$theme = array(
    'name' => $theme_name,
    'something' => $somevar
);

$twig = new Twig_Environment($loader);
$app["twig"]->addGlobal("theme", $theme);

在模板中,您可以输出此数组的命名元素:

{{ theme.name }}
{{ theme.something }}

HTH


1
投票

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());

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

 {{ text.lipsum(40) }}

0
投票

就那么简单:

$twig->addGlobal('themename', $variation);

在你刚才打电话的模板文件中

{{themename}}
© www.soinside.com 2019 - 2024. All rights reserved.