How can I define global variables inside a twig template file?

Amir Ajoudanian picture Amir Ajoudanian · Mar 10, 2015 · Viewed 22.4k times · Source

Is it possible to set global variables in a twig file, so that I can access that variables from other files, macros and blocks.

For example, I want to have variables.twig file and in it set my variables and then I can include it in other templates.

I know that setting global variables is possible from the framework (e.g. Symfony) but I want a solution using twig features only.

Answer

Alain Tiemblo picture Alain Tiemblo · Mar 10, 2015

Using Symfony2 configuration

If you are using Symfony2, you can set globals in your config.yml file:

# app/config/config.yml
twig:
    # ...
    globals:
        myStuff: %someParam%

And then use {{ myStuff }} anywhere in your application.


Using Twig_Environment::addGlobal

If you are using Twig in another project, you can set your globals directly in the environment:

$twig = new Twig_Environment($loader);
$twig->addGlobal('myStuff', $someVariable);

And then use {{ myStuff }} anywhere in your application.


Using a Twig extension

If you have lots of global variables and want to specify a set of globals for a particular part of your application only, you can create a Twig extension:

class Some_Twig_Extension extends Twig_Extension implements Twig_Extension_GlobalsInterface
{
    public function getGlobals()
    {
        return array(
            'someStuff' => $this->myVar,
            // ...
        );
    }

    // ...
}

Then import it in your environment only when required:

$twig = new Twig_Environment($loader);
$twig->addExtension(new Project_Twig_Extension());

And still use {{ myStuff }} anywhere in your application.

Using a Twig template

When you're including a piece of Twig code, you're only including the rendered view coming from that code, not the code itself. So it is by design not possible to include a set of variables the way you are looking for.