Set locale on the fly in laravel4

点点圈 提交于 2019-12-19 03:20:51

问题


After searching through the documentation from laravel 4 I see that the way to set a language is to do

App::setLocale('en');

But how do I use this in combination with for example a language switcher on my website that a visitor can click on to change the language on the fly? and to remember this with a cookie or something?

It seems that in laravel 3 it was much easier but since im new to laravel I don't know how to figure this out so if someone knows what to do and can help me out it would be great :)


回答1:


This is a way:

Create a route for your language selector:

Route::get('language/{lang}', 
           array(
                  'as' => 'language.select', 
                  'uses' => 'LanguageController@select'
                 )
          );

Create your language selectors links in Laravel Blade's view:

<html><body>

    Please select a Language:

    {{link_to_route('language.select', 'English', array('en'))}}

    {{link_to_route('language.select', 'Portuguese', array('pt'))}}

</body></html>

A Controller:

Class LanguageController extends BaseController {

    public function select($lang)
    {
        Session::put('lang', $lang);

        return Redirect::route('home');
    }

}

Then in your app/start/global.php you can:

App::setLocale(Session::get('lang', 'en'));



回答2:


There is great library for Laravel that allows you to handle locales flexible - mcamara laravel localization. In readme of the project you can find example how to implement such a switcher.



来源:https://stackoverflow.com/questions/20273956/set-locale-on-the-fly-in-laravel4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!