laravel 在 laravel4 中即时设置语言环境

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20273956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:42:57  来源:igfitidea点击:

Set locale on the fly in laravel4

phplocalizationlaravellaravel-4

提问by Reshad

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

在从 laravel 4 搜索文档后,我看到设置语言的方法是

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

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

回答by Antonio Carlos Ribeiro

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:

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

<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/start/global.php 你可以:

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

回答by qbasso

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.

Laravel 有一个很棒的库,可以让您灵活地处理语言环境 - mcamara laravel 本地化。在项目的自述文件中,您可以找到如何实现此类切换器的示例。