Symfony2 language selector

前端 未结 5 690
深忆病人
深忆病人 2020-12-24 09:18

I would like to integrate a simple HTML form allowing the user to change Symfony2 web application\'s language (i.e. from page en/faq go to fr/faq). How to do it in a proper

5条回答
  •  梦毁少年i
    2020-12-24 09:48

    I have not done this with a form, but simply with small flag images at the top of the screen. Each flag is a link to the current page, but with the two-letter language code in the URL replaced by the language of the respective flag. My layout template has the following code:

    {% for language, description in languages %}
        
        
        
    {% endfor %}
    

    The replaceLanguageInUrl function is defined in my Twig extension class:

    public function getFunctions()
    {
        return array(
            'replaceLanguageInUrl' => new \Twig_Function_Method($this, 'replaceLanguageInUrl'),
        );
    }    
    
    public function replaceLanguageInUrl($currentLanguage, $newLanguage, $url)
    {
    
        //EDIT BEGIN
        if (strpos($url,$currentLanguage) == false) {
            $url = getBaseUrl($url).'/'.$currentLanguage;
        }
        //EDIT END
        return str_replace('/' . $currentLanguage . '/', '/' . $newLanguage . '/', $url);
    }
    

    When a flag is clicked, the same page is loaded, but in the new language. This will also automatically set the new language in the session.

提交回复
热议问题