How to pass a php variable to twig template
Asked Answered
R

3

5

I have found quite a few discussions on this but I can't seem to make it work. I define the variable in php this way

$theme_name = 'layout1';

So I tried the following to get 'layout1' to show in my CMS template using {{ theme.name }} by each one of the following, one at a time, but none of them worked. The ones with $twig gave undefined variable 'twig'.

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

So where am I going wrong?

Romola answered 2/2, 2016 at 18:41 Comment(2)
where is the call (code) of your template file ?Magnetism
I have this in my cms template {{ theme.name }} but nothing shows where this code is.Romola
S
3

Simple as that:

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

and in you template file you just call

{{themename}}
Secern answered 3/2, 2016 at 9:3 Comment(1)
Thanks. I'm trying to understand this command. Does it define a global twig variable called 'themename' with contents of a previous defined php variable called $variation? It's hard to find the defintion of this on sensiolabs site, although to coders it's probably obvious.Romola
R
3

You could also add the whole array to Twig:

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

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

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

In your template, you may then output named elements of this array:

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

HTH

Romina answered 3/2, 2016 at 9:33 Comment(0)
C
2

The Twig documentation covers this.

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

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

A global variable is like any other template variable, except that it's available in all templates and macros:

 $twig = new Twig_Environment($loader);
 $twig->addGlobal('text', new Text());

You can then use the text variable anywhere in a template:1

 {{ text.lipsum(40) }}
Constitute answered 2/2, 2016 at 19:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.