How to Inject Variables into all Templates (i.e. global Variables)
Warning: You are browsing the documentation for Symfony 2.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.1 (the current stable version).
Sometimes you want a variable to be accessible to all the templates you use.
This is possible inside your app/config/config.yml
file:
1 2 3 4 5
# app/config/config.yml
twig:
# ...
globals:
ga_tracking: UA-xxxxx-x
Now, the variable ga_tracking
is available in all Twig templates:
1
<p>The google tracking code is: {{ ga_tracking }}</p>
It's that easy!
Using Service Container Parameters
You can also take advantage of the built-in Service Container system, which lets you isolate or reuse the value:
1 2 3
# app/config/parameters.yml
parameters:
ga_tracking: UA-xxxxx-x
1 2 3 4
# app/config/config.yml
twig:
globals:
ga_tracking: '%ga_tracking%'
The same variable is available exactly as before.
Referencing Services
Instead of using static values, you can also set the value to a service. Whenever the global variable is accessed in the template, the service will be requested from the service container and you get access to that object.
Note
The service is not loaded lazily. In other words, as soon as Twig is loaded, your service is instantiated, even if you never use that global variable.
To define a service as a global Twig variable, prefix the string with @
.
This should feel familiar, as it's the same syntax you use in service configuration.
1 2 3 4 5
# app/config/config.yml
twig:
# ...
globals:
user_management: '@app.user_management'