Creative Commons License
This work is licensed under a
Creative Commons
Attribution-Share Alike 3.0
Unported License.

Master Symfony2 fundamentals

Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).
trainings.sensiolabs.com

Symfony hosting done right

ServerGrove, outstanding support at the right price for your Symfony hosting needs.
servergrove.com

Discover the SensioLabs Support

Access to the SensioLabs Competency Center for an exclusive and tailor-made support on Symfony
sensiolabs.com

How to Inject Variables into all Templates (i.e. Global Variables)

How to Inject Variables into all Templates (i.e. Global Variables)

Sometimes you want a variable to be accessible to all the templates you use. This is possible inside your app/config/config.yml file:

  • YAML
    1
    2
    3
    4
    5
    # app/config/config.yml
    twig:
        # ...
        globals:
            ga_tracking: UA-xxxxx-x
    
  • XML
    <!-- app/config/config.xml -->
    <twig:config ...>
        <!-- ... -->
        <twig:global key="ga_tracking">UA-xxxxx-x</twig:global>
    </twig:config>
  • PHP
    1
    2
    3
    4
    5
    6
    7
    // app/config/config.php
    $container->loadFromExtension('twig', array(
         // ...
         'globals' => array(
             '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! You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:

1
2
3
# app/config/parameters.yml
parameters:
    ga_tracking: UA-xxxxx-x
  • YAML
    1
    2
    3
    4
    # app/config/config.yml
    twig:
        globals:
            ga_tracking: "%ga_tracking%"
    
  • XML
    <!-- app/config/config.xml -->
    <twig:config ...>
        <twig:global key="ga_tracking">%ga_tracking%</twig:global>
    </twig:config>
  • PHP
    1
    2
    3
    4
    5
    6
    // app/config/config.php
    $container->loadFromExtension('twig', array(
         'globals' => array(
             '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.