Switch Locale Programmatically in Symfony 7

Switch Locale Programmatically in Symfony 7

Symfony, a widely used PHP framework, offers support for internationalization (i18n) and localization (l10n). This enables developers to build applications that serve users globally. At times, it becomes necessary to dynamically switch the application's locale temporarily for the execution of specific code. Think of an application that creates emails with Twig templates in various languages. Locale needs to be changed only rendering those templates. This tutorial explains how to switch locale programmatically in Symfony 7.

Symfony provides the LocaleSwitcher class, which allows changing the locale for the entire application. Later, the locale can be reset to its default value.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Locale;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Translation\LocaleSwitcher;

class TestController
{
    #[Route('/')]
    public function index(LocaleSwitcher $switcher): Response
    {
        echo Locale::getDefault(); // en

        $switcher->setLocale('de');
        echo Locale::getDefault(); // de

        $switcher->reset();
        echo Locale::getDefault(); // en

        return new Response();
    }
}

It is also possible to execute specific code with a particular locale without modifying the locale for the entire application.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Locale;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Translation\LocaleSwitcher;

class TestController
{
    #[Route('/')]
    public function index(LocaleSwitcher $switcher): Response
    {
        echo Locale::getDefault(); // en

        $switcher->runWithLocale('de', function () {
            echo Locale::getDefault(); // de
        });

        echo Locale::getDefault(); // en

        return new Response();
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.