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?
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;
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With