How to pass a php variable to twig template

17,308

Solution 1

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

Solution 2

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

Solution 3

Simple as that:

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

and in you template file you just call

{{themename}}
Share:
17,308
tyee
Author by

tyee

Updated on June 13, 2022

Comments

  • tyee
    tyee almost 2 years

    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?