Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an environment variable (from `.env` file) in custom Twig function in Symfony?

How can I use an environment variable from the .env file in a custom Twig function (\Twig_SimpleFunction) in Symfony 4?

like image 574
jpyzio Avatar asked Aug 31 '25 18:08

jpyzio


1 Answers

Here's an easier way (Symfony 4) that does not involve any custom extensions. In my case, I wanted to set the Google Tag Manager Id as an environment variable in the .env file:

GOOGLE_TAG_MANAGER_ID="GTM-AAA12XX"

Next, reference the environment variable in the config/packages/twig.yaml file:

twig:
    globals:
        google_tag_manager_id: '%env(GOOGLE_TAG_MANAGER_ID)%'

Now you can use the tag manager value in your Twig templates like this:

{{ google_tag_manager_id }}

For a production system, you may not have a .env file. In that case, set the variable in your Apache config file:

SetEnv GOOGLE_TAG_MANAGER_ID GTM-AAA12XX

I have not tested things with nginx config files, but I think this should work:

fastcgi_param GOOGLE_TAG_MANAGER_ID "GTM-AAA12XX";

For more details, see the Symfony documentation for Configuration Based on Environment Variables, and Environment Variable Processors. Environment Variable Processors let you do things like trim variables or set defaults.

like image 59
lfjeff Avatar answered Sep 02 '25 19:09

lfjeff