Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get browser locale automatically

Tags:

locale

symfony

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?

like image 465
mathieu_b Avatar asked Jul 10 '26 19:07

mathieu_b


2 Answers

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;
}
like image 79
b3da Avatar answered Jul 14 '26 00:07

b3da


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).

like image 38
Arco Voltaico Avatar answered Jul 14 '26 01:07

Arco Voltaico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!