Define Global Variables for Twig Templates in Symfony 7

Define Global Variables for Twig Templates in Symfony 7

Sometimes we may need to inject the same variable in all the Twig templates. It can be done on each controller by passing a variable to template. However, it is not a good solution. This tutorial shows how to define global variables for Twig templates in Symfony 7 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, the variable tracking_id will be injected automatically into all the Twig templates.

templates/test/index.html.twig

{{ tracking_id }}

Leave a Comment

Cancel reply

Your email address will not be published.