How to get config parameters in Symfony2 Twig Templates How to get config parameters in Symfony2 Twig Templates symfony symfony

How to get config parameters in Symfony2 Twig Templates


You can use parameter substitution in the twig globals section of the config:

Parameter config:

parameters:    app.version: 0.1.0

Twig config:

twig:    globals:        version: '%app.version%'

Twig template:

{{ version }}

This method provides the benefit of allowing you to use the parameter in ContainerAware classes as well, using:

$container->getParameter('app.version');


Easily, you can define in your config file:

twig:    globals:        version: "0.1.0"

And access it in your template with

{{ version }}

Otherwise it must be a way with an Twig extension to expose your parameters.


You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:

# app/config/parameters.ymlparameters:    ga_tracking: UA-xxxxx-x# app/config/config.ymltwig:    globals:        ga_tracking: "%ga_tracking%"

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

<p>The google tracking code is: {{ ga_tracking }}</p>

The parameter is also available inside the controllers:

$this->container->getParameter('ga_tracking');

You can also define a service as a global Twig variable (Symfony2.2+):

# app/config/config.ymltwig:    # ...    globals:        user_management: "@acme_user.user_management"

http://symfony.com/doc/current/templating/global_variables.html

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.