Set Default Locale in Symfony 6

Set Default Locale in Symfony 6

Symfony framework translate text in the application based on the locale of the user. If the user's locale cannot be determine then default locale is used. This tutorial shows how to set default locale in Symfony 6 application.

The default locale can set by using default_locale option under the framework key:

config/packages/translation.yaml

framework:
    default_locale: de

In order to test, create translation file for default locale:

translations/messages.de.yaml

hello_world: Hallo Welt

In your controller try to translate the message:

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;

class TestController
{
    #[Route('/')]
    public function index(TranslatorInterface $translator): Response
    {
        return new Response($translator->trans('hello_world'));
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.