How to Work with the User’s Locale

How to Work with the User’s Locale

The locale of the current user is stored in the request and is accessible via the Request object:

  1. use Symfony\Component\HttpFoundation\Request;
  2. public function index(Request $request)
  3. {
  4. $locale = $request->getLocale();
  5. }

To set the user’s locale, you may want to create a custom event listener so that it’s set before any other parts of the system (i.e. the translator) need it:

  1. public function onKernelRequest(RequestEvent $event)
  2. {
  3. $request = $event->getRequest();
  4. // some logic to determine the $locale
  5. $request->setLocale($locale);
  6. }

Note

The custom listener must be called before LocaleListener, which initializes the locale based on the current request. To do so, set your listener priority to a higher value than LocaleListener priority (which you can obtain running the debug:event kernel.request command).

Read Making the Locale “Sticky” during a User’s Session for more information on making the user’s locale “sticky” to their session.

Note

Setting the locale using $request->setLocale() in the controller is too late to affect the translator. Either set the locale via a listener (like above), the URL (see next) or call setLocale() directly on the translator service.

See the The Locale and the URL section below about setting the locale via routing.

The Locale and the URL

Since you can store the locale of the user in the session, it may be tempting to use the same URL to display a resource in different languages based on the user’s locale. For example, http://www.example.com/contact could show content in English for one user and French for another user. Unfortunately, this violates a fundamental rule of the Web: that a particular URL returns the same resource regardless of the user. To further muddy the problem, which version of the content would be indexed by search engines?

A better policy is to include the locale in the URL using the special _locale parameter:

  • Annotations

    1. // src/Controller/ContactController.php
    2. namespace App\Controller;
    3. // ...
    4. class ContactController extends AbstractController
    5. {
    6. /**
    7. * @Route(
    8. * "/{_locale}/contact",
    9. * name="contact",
    10. * requirements={
    11. * "_locale": "en|fr|de",
    12. * }
    13. * )
    14. */
    15. public function contact()
    16. {
    17. }
    18. }
  • YAML

    1. # config/routes.yaml
    2. contact:
    3. path: /{_locale}/contact
    4. controller: App\Controller\ContactController::index
    5. requirements:
    6. _locale: en|fr|de
  • XML

    1. <!-- config/routes.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <routes xmlns="http://symfony.com/schema/routing"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/routing
    6. https://symfony.com/schema/routing/routing-1.0.xsd">
    7. <route id="contact" path="/{_locale}/contact">
    8. controller="App\Controller\ContactController::index">
    9. <requirement key="_locale">en|fr|de</requirement>
    10. </route>
    11. </routes>
  • PHP

    1. // config/routes.php
    2. use App\Controller\ContactController;
    3. use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
    4. return function (RoutingConfigurator $routes) {
    5. $routes->add('contact', '/{_locale}/contact')
    6. ->controller([ContactController::class, 'index'])
    7. ->requirements([
    8. '_locale' => 'en|fr|de',
    9. ])
    10. ;
    11. };

When using the special _locale parameter in a route, the matched locale is automatically set on the Request and can be retrieved via the [getLocale()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/HttpFoundation/Request.php "Symfony\Component\HttpFoundation\Request::getLocale()") method. In other words, if a user visits the URI /fr/contact, the locale fr will automatically be set as the locale for the current request.

You can now use the locale to create routes to other translated pages in your application.

Tip

Define the locale requirement as a container parameter to avoid hardcoding its value in all your routes.

Setting a Default Locale

What if the user’s locale hasn’t been determined? You can guarantee that a locale is set on each user’s request by defining a default_locale for the framework:

  • YAML

    1. # config/packages/translation.yaml
    2. framework:
    3. default_locale: en
  • XML

    1. <!-- config/packages/translation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:framework="http://symfony.com/schema/dic/symfony"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony
    9. https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
    10. <framework:config default-locale="en"/>
    11. </container>
  • PHP

    1. // config/packages/translation.php
    2. $container->loadFromExtension('framework', [
    3. 'default_locale' => 'en',
    4. ]);

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.