How to set global variables in Twig with Symfony [Twig,Symfony]

Verification environment Symfony3.4

This is how to set global variables for Twig using Symfony.
As far as I can tell from the manual, it can work with other versions as well.

Set global variables in the config file.

Basically, you can set them by simply adding the following to your config.

# app/config/config.yml
twig:
    globals:
        main_color: 'red'
...

# sample twig
{{ dump(main_color) }}

// result red

It is very simple. Of course, you can also use the parameters in the service container.

# Using Service Container Parameters
# app/config/parameters.yml
parameters:
    main_color: 'red'

# app/config/config.yml
twig:
    globals:
        main_color: '%main_color%'

The above is the basic usage.

How to make global variables variable instead of fixed?


It is possible to control the value of a global variable by setting a service.
Here is a simple sample.

// ColorDefine.php
...

class ColorDefine
{
    public function getColor($main)
    {
        $color = $main;

        return $color;
    }
}

# app/config/config.yml
twig:
    globals:
        # To define a service as a global Twig variable, prefix the string with @.
        main_color: '@AppBundle\Service\ColorDefine'

# twig
{{ dump(main_color.getColor('green')) }}

result green

 
It allows you to call service on Twig as shown above.
You can also pass arguments, so I think it is very extensible. However, there is a caveat that since it is set to global, the service will be loaded even if it is not being used in Twig.

This is a summary of how to pass global variables to Twig.