I use Symfony 3. My website is in 2 languages, French and English and people can switch via a select form. Default language is French. Main URL are: example.com/fr for French version and example.com/en for English version
Well, now, I will like when the user arrives to the website to detect his browser language and redirect to the correct language automatically. Exemple, if the browser is in French, he is redirected to the French version : example.com/fr Else he is redirected to the English version: example.com/en
Is there a way to do that properly?
Thank you for your help
If you don't want to rely on other bundles like JMSI18nRoutingBundle you have to make yourself familiar with Symfony's Event system, e.g. by reading up on the HttpKernel.
For your case you want to hook into the
kernel.request
event.In your custom EventListener you can listen to that event add information to the Request-object used in your router. It could look something like this:
This listener will check the
Accept-Language
header of the request and use the Negotiation\LanguageNegotiator to determine the best locale. Be careful as I didn't add the use statements, but they should be fairly obvious.For a more advanced version you can just read the source for the LocaleChoosingListener from JMSI18nRoutingBundle.
Doing this is usually only required for the frontpage, which is why both the example I posted and the one from the JMSBundle exclude all other paths. For those you can just use the special parameter
_locale
as described in the documentation:https://symfony.com/doc/current/translation/locale.html#the-locale-and-the-url
The Symfony documentation also contains an example how to read the locale and make it sticky in a session using a Listener: https://symfony.com/doc/current/session/locale_sticky_session.html This example also shows how to register the Listener in your services.yml.