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

7

35

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

Prothallus answered 4/3, 2018 at 0:54 Comment(1)
@jakub you might want to consider to change the "accepted" answer flag to lfjeff answer further down: https://mcmap.net/q/422808/-using-an-environment-variable-from-env-file-in-custom-twig-function-in-symfony-4Melanoid
T
33

It's possible to access env vars in a twig template without any additional configuration:

{{ app.request.server.get('MY_ENV_VAR') }}

Thadthaddaus answered 15/2, 2021 at 1:19 Comment(2)
This works perfectly fine, but does not support defaults set in parameters: env(MY_ENV_VAR): someDefaulValue would be ignore in this case.Dorise
Interestingly, this is not working for me in a docker container. When I run the app code outside of the container it works, but with docker it doesn't. The container is getting all of the environment variables ... connecting to the container, I see that my var is present when I call set, but app.request.server.get('MY_ENV_VAR') isn't finding it.Zippora
C
107

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.

Careworn answered 19/5, 2018 at 5:26 Comment(1)
This way worked for me for a docker container. For some reason, app.request.server.get('MY_ENV_VAR') was returning a blank string, even though the env vars were all present in the running container.Zippora
T
33

It's possible to access env vars in a twig template without any additional configuration:

{{ app.request.server.get('MY_ENV_VAR') }}

Thadthaddaus answered 15/2, 2021 at 1:19 Comment(2)
This works perfectly fine, but does not support defaults set in parameters: env(MY_ENV_VAR): someDefaulValue would be ignore in this case.Dorise
Interestingly, this is not working for me in a docker container. When I run the app code outside of the container it works, but with docker it doesn't. The container is getting all of the environment variables ... connecting to the container, I see that my var is present when I call set, but app.request.server.get('MY_ENV_VAR') isn't finding it.Zippora
S
17

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.

Shooin answered 6/3, 2018 at 18:26 Comment(0)
K
3

Now you can do it directly.

{{ app.request.server.get('APP_ENV') }}

Kirby answered 26/7, 2021 at 12:50 Comment(0)
E
2

Using DotEnv as well, I just went with:

$twig = new \Twig\Environment($loader); // or however you access your Twig instance.
$twig->addFunction(
    new \Twig\TwigFunction('getenv', function ($key) {
        return getenv($key);
    })
);

And then in a template I'll just use {{ getenv('SOME_ENV_VARIABLE') }}.

Elutriate answered 26/3, 2020 at 16:6 Comment(0)
S
0

add it to your twig.yaml as a global variable like so, then you can use it anywhere:

twig: 
  globals: 
    env: '%env(SYMFONY_ENV)%'
Sonar answered 12/11, 2021 at 12:4 Comment(3)
Comment to myself though: This is apparently a bad idea, see the downvoted answer here: #6788395Sonar
could you clarify why that's a bad idea? IMHO, If you don't need access to this variable from service container, that should be fineContinental
@Sonar I dont see why this is a bad approach, considering the documentation. You are accessing env and only one specific paramter, not the app service container as statet in your linked answer.Spurge
C
-3

You can use it anywhere in the project like this

$_ENV["APP_ENV"]
Clangor answered 30/3, 2021 at 18:9 Comment(1)
Well it works? Why not? Also allows you to check the value and assign a default value: $this->oauthGoogleId = $_ENV['OAUTH_GOOGLE_ID'] ?? '';Goolsby

© 2022 - 2024 — McMap. All rights reserved.