Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Translation
  4. How to Work with the User's Locale
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

Table of Contents

  • The Locale and the URL
  • Setting a Default Locale

How to Work with the User's Locale

Edit this page

Warning: You are browsing the documentation for Symfony 4.3, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

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
2
3
4
5
6
use Symfony\Component\HttpFoundation\Request;

public function index(Request $request)
{
    $locale = $request->getLocale();
}

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
2
3
4
5
6
7
public function onKernelRequest(RequestEvent $event)
{
    $request = $event->getRequest();

    // some logic to determine the $locale
    $request->setLocale($locale);
}

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 How to Work with the User's Locale 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:

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

    <route id="contact" path="/{_locale}/contact">
        controller="App\Controller\ContactController::index">
        <requirement key="_locale">en|fr|de</requirement>
    </route>
</routes>
1
2
3
4
5
6
7
8
9
10
11
12
// config/routes.php
use App\Controller\ContactController;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

return function (RoutingConfigurator $routes) {
    $routes->add('contact', '/{_locale}/contact')
        ->controller([ContactController::class, 'index'])
        ->requirements([
            '_locale' => 'en|fr|de',
        ])
    ;
};

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() 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
  • XML
  • PHP
1
2
3
# config/packages/translation.yaml
framework:
    default_locale: en
1
2
3
4
5
6
7
8
9
10
11
12
<!-- config/packages/translation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:framework="http://symfony.com/schema/dic/symfony"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd
        http://symfony.com/schema/dic/symfony
        https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

    <framework:config default-locale="en"/>
</container>
1
2
3
4
// config/packages/translation.php
$container->loadFromExtension('framework', [
    'default_locale' => 'en',
]);
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:
The life jacket for your team and your project

The life jacket for your team and your project

Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of Arkadiusz Rzadkowolski, a Symfony contributor

Thanks Arkadiusz Rzadkowolski (@flies) for being a Symfony contributor

4 commits • 161 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia