How to retrieve .env variables directly from a Twig view in Symfony 5

In Symfony 3, we used to store parameters that we needed globally accessible in the parameters.yaml file, like the google analytics ID, the recaptcha id etc. However in Symfony 4, the introduction of the .env file moved all those parameters that we used to place in that file, to the new one. Till the date, for some developers it isn't so clear how to obtain these values now within a Twig view.

In this short article, we will show you 3 ways to obtain the value from your .env file using Twig in your Symfony 5 project.

Pass the parameter to the view from the controller

The most obvious solution to obtain a .env parameter inside a twig view is to simply pass it from the controller just as a regular variable:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class PagesController extends AbstractController
{
    /**
     * @Route("/", name="index")
     */
    public function index(): Response
    {
        return $this->render('pages/index.html.twig', [
            'environment' => $_ENV["APP_ENV"],
        ]);
    }
}

Then in the view:

{% extends 'base.html.twig' %}

{% block title %}Index Page{% endblock %}

{% block body %}
    {{ environment }}
{% endblock %}

Using a Twig Custom Function

The other option, which certainly suits better in most of the cases, is to create a new twig custom function that returns the environment variable on your views directly. Create the new extension if you don't have any created and register the new function get_env:

<?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('get_env', [$this, 'getEnvironmentVariable']),
        ];
    }
    
    /**
     * Return the value of the requested environment variable.
     * 
     * @param String $varname
     * @return String
     */
    public function getEnvironmentVariable($varname)
    {
        return $_ENV[$varname];
    }
}

After creating the file (or registering the new function), you should be able to use it now on your Twig views like this:

{# Outputs in this case: dev #}
{{ get_env("APP_ENV") }}

With this approach, you shouldn't need anymore to create a new key in the parameters.yaml file obtaining the parameter with ENV.

Register environment variable on Twig Globals

If you don't have to work with a lot of environment variables, this option is probably the easiest one. In Symfony, you can register global variables in Twig through the configuration file (app/config/packages/twig.yaml) under the global key:

# app/config/packages/twig.yaml
twig:
    default_path: '%kernel.project_dir%/templates'
    
    # Register your global variables under the globals key:
    globals:
        mycustom_variable: 12345
        # Obtain it from the .env file:
        app_environment: '%env(APP_ENV)%'

In this case, you can obtain the value from the defined key as a global variable in Twig like this:

{# Outputs: 12345 #}
{{ mycustom_variable }}
{# Outputs: dev #}
{{ app_environment }}

Happy coding ❤️!

This could interest you

Become a more social person