3

I have

config.yml

#Here locale is en
translator:      { fallback: %locale% }
...
session:
    default_locale: %locale%

routing.yml

AcmeDemoBundle_homepage:
    pattern:  /{_locale}/index
    defaults: { _controller: AcmeDemoBundle:Default:index, _locale: de}
    requirements:
    _locale: en|de

So here by manually typing URL will lead /en/index to English and /de/index to German.

How we can make automatically go to german, if browser Accept language is de_DE or de(German), else go to english(all other browser Accept languages)?

Carlos Granados
  • 11,273
  • 1
  • 38
  • 44
Justin John
  • 9,223
  • 14
  • 70
  • 129

2 Answers2

5

Basically you can do something like that

$this->get('session')->setLocale(
    $request->getPreferredLanguage(array('en', 'de'))
);

and its should do the trick. But yeah add it in every action can be hard... that why you can create own kernel event listener.

Those links can be helpful I think:

Symfony2 wrong locale detection?

http://symfony.com/doc/current/cookbook/service_container/event_listener.html

Community
  • 1
  • 1
l3l0
  • 3,363
  • 20
  • 19
3

I have been using the JMSI18nRoutingBundle, which automatically handles the locale in URLs. On the default URL, it will optionally use the preferred locale.

The Kernel event listener is a good option for which you can find information in the documentation. However, keep in mind that you should only trigger it on new sessions to make sure the users can still manually select the language they view the site in.

Louis-Philippe Huberdeau
  • 5,341
  • 1
  • 19
  • 22