Using an environment variable (from `.env` file) in custom Twig function in Symfony 4

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.


Install the Dotenv component so you can use the getenv() function:

<?php
// src/Twig/AppExtension.php

namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
{
    public function getFunctions(): array
    {
        return [
            new TwigFunction('my_function', [$this, 'myFunction']),
        ];
    }

    public function myFunction($varname)
    {
        $value = getenv($varname);

        // Do something with $value...

        return $value;
    }
}

If you just want to return the value of the environment variable, you can simplify the code like this:

<?php
// src/Twig/AppExtension.php

namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
{
    public function getFunctions(): array
    {
        return [
            new TwigFunction('my_function', 'getenv'),
        ];
    }
}

Either way, in Twig you can then do:

{{ my_function('APP_ENV') }}

{% if my_function('MAILER_URL') == 'null://localhost' %}
    Mailer URL not set!
{% endif %}

{# etc. #}

A better function name would of course be e.g. getenv. Here I used my_function so that our own code wouldn't be confused with the getenv() function provided by the Dotenv component.

The getenv() function returns false if the environment variable isn't found.