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

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.


It seems that you can assign global READONLY variables in your top-level template and use them in all underlying templates. But you can't override them of course. It covers my case, maybe will be useful for somebody else.

base.html.twig

<!DOCTYPE html>
{# assign global vars here #}
{% set myReadonlyJar = your_custom_ext_twig_function() %} 
<html>
    <body>
        {% block body %}{% endblock %}
    </body>
</html>

my_page.twig

{% extends 'stack/base.html.twig' %}

{% block body %}
    {{ myReadonlyJar.v1 }}

    {{ myReadonlyJar.v2 }}
    {{ include('stack/deep.twig') }}
{% endblock %}

deep.twig

Check top vars very deep inside: <br>
{{ myReadonlyJar.v2 }}

Since Symfony 4, you can set the globals in config/packages/twig.yaml.

# config/packages/twig.yaml
twig:
    # ...
    globals:
        ga_tracking: 'UA-xxxxx-x'