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. # app/config/config.yml 
  2. twig: 
  3.     # ... 
  4.     globals: 
  5.         ga_tracking: UA-xxxxx-x 

Now, the variable ga_tracking is available in all Twig templates:

  1. <p>Our google tracking code is: {{ ga_tracking }} </p> 

It's that easy! You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:

  1. ; app/config/parameters.yml 
  2. [parameters] 
  3.     ga_tracking: UA-xxxxx-x
  1. # app/config/config.yml 
  2. twig: 
  3.     globals: 
  4.         ga_tracking: %ga_tracking% 

The same variable is available exactly as before.

More Complex Global Variables

If the global variable you want to set is more complicated - say an object - then you won't be able to use the above method. Instead, you'll need to create a Twig Extension and return the global variable as one of the entries in the getGlobals method.