Define Global Variables for Twig Templates in Symfony 6

Define Global Variables for Twig Templates in Symfony 6

Sometimes we may need to inject the same variable in all Twig templates. It can done on each controller by passing variable to template. However, it is not good solution. This tutorial shows how to define global variables for Twig templates in Symfony 6 application.

Global variables for Twig templates can be defined using globals option under the twig key:

config/packages/twig.yaml

twig:
    globals:
        tracking_id: 'XXXXX-YYYYY-ZZZZZ'

In our case, variable tracking_id will be injected automatically into all Twig templates.

templates/test/index.html.twig

{{ tracking_id }}

Leave a Comment

Cancel reply

Your email address will not be published.