0x1gene
0x1gene

Reputation: 3458

Symfony2 Set _locale in home page base on browser's configuration

My local works everywhere on my website but I cant tell the application the set the proper local on the root of the application.

For exemple :

If my website is http://mycompany.com I want that, when I enter this address the application guess what is my local and set it at the end of the url http://mycompany.com/en if the local exist on my application. Here en or fr and if not the default en

For now when i go to home page I always get english version but my browser is set in french

routing.yml :

_welcome:
    pattern:  /{_locale}
    defaults: { _controller: MyBundle:Default:landing, _locale: en }
    requirements:
        _locale: en|fr

Upvotes: 1

Views: 1097

Answers (2)

0x1gene
0x1gene

Reputation: 3458

With the help of many other questions related to locale and symfony2 I finally get want I want ! I guess it is not the perfect answer but at least it works !

My landing action is defined in my routing as _welcome route. It is this action that is loaded when I go to the url's root.

     /**
     * @Route("/landing")
     * @Template()
     */
    public function landingAction() {

        $localeAvailable = array('en', 'fr');
        //user language
        $localeUser = substr($this->getRequest()->getPreferredLanguage(), 0, 2);
        //application language
        $localeApp = $this->getRequest()->attributes->get('_locale');

        //Redirect to the good locale page 
        //only if the locale user is on our manager locale and it is not the current locale of the application
        if(in_array($localeUser, $localeAvailable) && $localeApp!=$localeUser){
            return $this->redirect($this->generateUrl("_welcome", array('_locale' => $localeUser)));
        }

        return array();
    }

Upvotes: 1

Emii Khaos
Emii Khaos

Reputation: 10085

See this question asked a few days ago and take a look at the first method in the language listener. It does exactly what you need. And take care of the right settings in config.yml

Upvotes: 1

Related Questions