在 laravel4 中即时设置语言环境

2022-01-08 00:00:00 localization php laravel laravel-4

从 laravel 4 中搜索文档后,我发现设置语言的方法是这样做

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

App::setLocale('en');

但是我如何将它与例如我网站上的语言切换器结合使用,访问者可以点击它来即时更改语言?并用 cookie 或其他东西记住这一点?

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?

似乎在 laravel 3 中这要容易得多,但由于我是 laravel 的新手,我不知道如何解决这个问题,所以如果有人知道该怎么做并且可以帮助我,那就太好了:)

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

推荐答案

这是一种方式:

为您的语言选择器创建路由:

Create a route for your language selector:

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

在 Laravel Blade 的视图中创建你的语言选择器链接:

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>

控制器:

Class LanguageController extends BaseController {

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

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

}

然后在你的 app/start/global.php 中你可以:

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

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

相关文章