3

I'm trying to internationalize my website using Symfony. This is my routing.yml:

index:
    pattern: /{_locale}
    defaults: { _controller: AppBundle:Index:index, _locale: en }
    requirements:
        _locale: en|fr

When the URL is just "/", "en" locale is set automatically, this is great but I want the browser locale. For exemple, if I'm in France and I type "/", I want redirect to "/fr/", etc.

Can you help me?

pagid
  • 13,559
  • 11
  • 78
  • 104
mathieu_b
  • 383
  • 1
  • 5
  • 19
  • Make the listener that listens to kernel.request and set prefered language, so simple. – malcolm Aug 29 '15 at 19:17
  • @malcolm Not so simple for me :D, can you be more specific? – mathieu_b Aug 29 '15 at 21:29
  • 1
    If you haven't read all the Symfony's documentation (at least about the related arguments) then is surely not simple understand what @malcolm wrote. PS: IMHO force the user redirect basing on browser language instead of allow a selection of the language is surely a bad approach – gp_sflover Aug 29 '15 at 22:29
  • @gp_sflover Yeah I'll read all doc, this is a good idea. Plenty of website redirect the user to his locale using http language accept in the request – mathieu_b Aug 29 '15 at 23:42

2 Answers2

3

you can get client locale and set redirection in controller

$clientLocale = strtolower(str_split($_SERVER['HTTP_ACCEPT_LANGUAGE'], 2)[0]);
switch ($clientLocale) {
    case 'fr':
        return $this->redirect($this->generateUrl('fr_route'));
    break;
    default:
        return $this->redirect($this->generateUrl('en_route'));
    break;
}
b3da
  • 573
  • 1
  • 5
  • 12
1

Based on b3da answer, I'll apply it only for the index route (as I think that is the main case when someone type your domain without params) and relying on my YML translations:

#routing.yml
index:
    path: /
    defaults:
        _controller: AppBundle:Pub:index


index2:
    path: /{_locale}
    defaults:
        _controller: AppBundle:Pub:index



#PubController.php
public function indexAction($_locale=null, Request $request) {
    if (!$_locale) {
        $browserLocale = strtolower(str_split($_SERVER['HTTP_ACCEPT_LANGUAGE'], 2)[0]);
            return $this->redirect($this->generateUrl('index2', ['_locale' => $browserLocale]));
    }
    return $this->render('AppBundle::index.html.twig', []);
}

If the local browser is not translated on your app/Resources/translation YMLs then it will render the texts using your fallback locale (app/config/parameters.yml).

Arco Voltaico
  • 860
  • 13
  • 29