Search code examples
phpvariablestwigglobaltemplating

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


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.


Solution

  • Using Symfony 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 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.