php 在 Laravel 中切换语言的最佳逻辑是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12708392/
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-08-25 04:05:14  来源:igfitidea点击:

What's the best logic for switching language in Laravel?

phplocalizationlaravel

提问by BenjaminRH

I'm using Laravel localization to provide two different languages. I've got all the path stuff set up, and mydomain.com/en/bla delivers English and stores the 'en' session variable, and mydomain.com/he/bla delivers Hebrew and stores the 'he' session variable. However, I can't figure out a decent way to provide a language-switching link. How would this work?

我正在使用 Laravel 本地化来提供两种不同的语言。我已经设置了所有路径内容,mydomain.com/en/bla 提供英语并存储“en”会话变量,而 mydomain.com/he/bla 提供希伯来语并存储“he”会话变量。但是,我想不出一个像样的方法来提供语言切换链接。这将如何运作?

采纳答案by BenjaminRH

I've solved my problem by adding this to the before filter in routes.php:

我通过将它添加到 routes.php 中的 before 过滤器解决了我的问题:

// Default language ($lang) & current uri language ($lang_uri)
$lang = 'he';
$lang_uri = URI::segment(1);

// Set default session language if none is set
if(!Session::has('language'))
{
    Session::put('language', $lang);
}

// Route language path if needed
if($lang_uri !== 'en' && $lang_uri !== 'he')
{
    return Redirect::to($lang.'/'.($lang_uri ? URI::current() : ''));
}
// Set session language to uri
elseif($lang_uri !== Session::get('language'))
{
    Session::put('language', $lang_uri);
}

// Store the language switch links to the session
$he2en = preg_replace('/he\//', 'en/', URI::full(), 1);
$en2he = preg_replace('/en\//', 'he/', URI::full(), 1);
Session::put('he2en', $he2en);
Session::put('en2he', $en2he);

回答by stormpat

This is a post i posted originally on the laravel forums, but maybe it will help somebody else, so i post it here also.

这是我最初发布在 Laravel 论坛上的帖子,但也许它会帮助其他人,所以我也在这里发布。

I had some trouble with building a easy language switcher for my app, and the info on the forums where a little bit old (some posts), so i made this simple piece of code that makes it supereasy to change language on your app on the fly.

我在为我的应用程序构建一个简单的语言切换器时遇到了一些麻烦,而且论坛上的信息有点旧(一些帖子),所以我制作了这段简单的代码,使在应用程序上更改语言变得非常容易飞。

I have the language strings in my views as following:

我的视图中有如下语言字符串:

{{ __('languagefile.the_language_string'); }}

And I get the languages with a URL, i think this is the best way, also its good for seo and for links that people share. Example:

而且我通过 URL 获取语言,我认为这是最好的方式,也有利于 seo 和人们共享的链接。例子:

www.myapp.com/fi/support (Finnish)
www.myapp.com/en/support (English)
www.myapp.com/sv/support (Swedish)

Ok, so the problem was that i wanted a easy way to change the language on the fly, without having to mess with sessions and cookies. Heres how i made it:

好的,所以问题是我想要一种简单的方法来即时更改语言,而不必弄乱会话和 cookie。继承人我是如何做到的:

Make a library in your libraries folder called chooselang.php

在您的库文件夹中创建一个名为chooselang.php 的

Insert this code inside:

在里面插入这段代码:

class Chooselang extends HTML {
    /**
     * Generate a Language changer link.
     *
     * <code>
     *      // Generate a link to the current location,
     *      // but still change the site langauge on the fly
     *      // Change $langcode to desired language, also change the Config::set('application.language', 'YOUR-LANG-HERE')); to desired language
     *      // Example
     *      echo Chooselang::langslug(URI::current() , $langcode = 'Finnish' . Config::set('application.language', 'fi'));
     * </code>
     *
     * @param  string  $url
     * @param  string  $langcode
     * @param  array   $attributes
     * @param  bool    $https
     * @return string
     */

    public static function langslug($url, $langcode = null, $attributes = array(), $https = null)
    {
        $url = URL::to($url, $https);

        if (is_null($langcode)) $langcode = $url;

        return '<a href="'.$url.'"'.static::attributes($attributes).'>'.static::entities($langcode).'</a>';
    }

}

After this you are ready for getting your url switcher URL:s generated. Simply add them as you whould any other Blade links.

在此之后,您就可以开始生成您的 url 切换器 URL:s。只需像添加任何其他 Blade 链接一样添加它们即可。

Example how to generate links for Finnish, Swedish and English (with Blade)

示例如何为芬兰语、瑞典语和英语生成链接(使用 Blade)

  {{ Chooselang::langslug(URI::current() , $langcode = 'Fin' . Config::set('application.language', 'fi')); }}
  {{ Chooselang::langslug(URI::current() , $langcode = 'Swe' . Config::set('application.language', 'sv')); }}
  {{ Chooselang::langslug(URI::current() , $langcode = 'Eng' . Config::set('application.language', 'en')); }}

The above will generate URL:s that are always on the current page, and change the lang slug to the one you want. This way the language changes to the one you want, and the user naturally stays on the same page. The default language slug is never added to the url.

以上将生成始终在当前页面上的 URL:s,并将 lang slug 更改为您想要的。通过这种方式,语言会更改为您想要的语言,并且用户自然会停留在同一页面上。默认语言 slug 永远不会添加到 url。

Generated urls look something like:

生成的网址看起来像:

<a href="http://localhost/laravel/public/support">Fin</a>
<a href="http://localhost/laravel/public/sv/support">Swe</a>
<a href="http://localhost/laravel/public/en/support">Eng</a>

PS. The links are specially useful if you add them to your master template file.

附注。如果您将链接添加到主模板文件中,这些链接将特别有用。

回答by PapaSmurf

You could have a Route to hand language change, for example:

您可以使用 Route to hand language change,例如:

Route::get('translate/(:any)', 'translator@set');

Route::get('translate/(:any)', 'translator@set');

Then in the setaction in the translatorcontroller could alter the session, depending on the language code passed via the URL.

然后在控制器的set动作中translator可以改变会话,这取决于通过 URL 传递的语言代码。

You could also alter the configuration setting by using

您还可以通过使用更改配置设置

Config::set('application.language', $url_variable');

Config::set('application.language', $url_variable');

Controller Example - translate.php

控制器示例 - translate.php

public function action_set($url_variable)
{
     /* Your code Here */
}

回答by Dexture

Just in case for future users if you want to use package for localization There is a great package at https://github.com/mcamara/laravel-localization. which is easy to install and has many helpers.

如果您想使用包进行本地化,以防将来的用户使用https://github.com/mcamara/laravel-localization 上有一个很棒的包。它易于安装并且有很多助手。

回答by bgies

This question still comes in Google search, so here's the answer if you're using Laravel 4 or 5, and mcamara/laravellocalization.

这个问题仍然出现在谷歌搜索中,所以如果你使用 Laravel 4 或 5,以及 mcamara/laravellocalization,这里是答案。

<ul>
    <li class="h5"><strong><span class="ee-text-dark">{{ trans('common.chooselanguage') }}:</span></strong> </li>
        @foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
            <li>
               <a rel="alternate" hreflang="{{$localeCode}}" href="{{LaravelLocalization::getLocalizedURL($localeCode) }}">
                   <img src="/img/flags/{{$localeCode}}.gif" /> {{{ $properties['native'] }}}
               </a>
           </li>
        @endforeach
</ul>

NOTE that this example shows flags (in public/img/flags/{{locale}}.gif), and to use it you will need a bit of .css, but you can modify it to display the text if you want...

请注意,此示例显示了标志(在 public/img/flags/{{locale}}.gif 中),要使用它,您将需要一些 .css,但如果需要,您可以修改它以显示文本.. .

FYI. The mcamara/laravellocalization documentation has examples and a LOT of helpers, so look through the documentation on github. (https://github.com/mcamara/laravel-localization)

供参考。mcamara/laravellocalization 文档有示例和大量帮助程序,因此请查看 github 上的文档。( https://github.com/mcamara/laravel-localization)

回答by GTCrais

I've been doing it like this:

我一直这样做:

$languages = Config::get('lang.languages'); //returns array('hrv', 'eng')

$locale = Request::segment(1); //fetches first URI segment

//for default language ('hrv') set $locale prefix to "", otherwise set it to lang prefix
if (in_array($locale, $languages) && $locale != 'hrv') {
    App::setLocale($locale);
} else {
    App::setLocale('hrv');
    $locale = null;
}

// "/" routes will be default language routes, and "/$prefix" routes will be routes for all other languages
Route::group(array('prefix' => $locale), function() {

    //my routes here

});

Source: http://forumsarchive.laravel.io/viewtopic.php?pid=35185#p35185

来源:http: //forumsarchive.laravel.io/viewtopic.php?pid=35185#p35185

回答by RDK

Try use Session's. Somthing like this:

尝试使用 Session 的。像这样的东西:

Controller:

控制器:

 class Language_Controller extends Base_Controller {

        function __construct(){
            $this->action_set();
            parent::__construct();
        }

       private function checkLang($lang = null){
         if(isset($lang)){
           foreach($this->_Langs as $k => $v){
             if(strcmp($lang, $k) == 0) $Check = true;
           }
       }
        return isset($Check) ? $Check : false;
       }

       public function action_set($lang = null){
        if(isset($lang) && $this->checkLang($lang)){
            Session::put('lang', $lang);
            $this->_Langs['current'] = $lang;
            Config::set('application.language', $lang);
        } else {
            if(Session::has('lang')){
                Config::set('application.language', Session::get('lang'));
                $this->_Langs['current'] = Session::get('lang');
            } else {
                $this->_Langs['current'] = $this->_Default;
            }
        }
        return Redirect::to('/');
    }
}

In Route.php:

在 Route.php 中:

Route::get('lang/(:any)', 'language@set');

回答by Terumi

What I'm doing consists of two steps: I'm creating a languages table which consists of these fields:

我所做的包括两个步骤:我正在创建一个包含以下字段的语言表:

id | name | slug

身 | 姓名 | 蛞蝓

which hold the data im gonna need for the languages for example

例如,它保存了我需要的语言数据

1 | greek | gr

1 | 希腊语 | 克

2 | english | en

2 | 英文 | 恩

3 | deutch | de

3 | 德语 | 德

The Language model I use in the code below refers to that table.

我在下面的代码中使用的语言模型是指该表。

So, in my routes.php I have something like:

所以,在我的 routes.php 中,我有类似的东西:

//get the first segment of the url
$slug = Request::segment(1);   
$requested_slug = "";

//I retrieve the recordset from the languages table that has as a slug the first url segment of request
$lang = Language::where('slug', '=', $slug)->first();

//if it's null, the language I will retrieve a new recordset with my default language
$lang ? $requested_slug = $slug :  $lang = Language::where('slug', '=', **mydefaultlanguage**')->first();

//I'm preparing the $routePrefix variable, which will help me with my forms
$requested_slug == ""? $routePrefix = "" : $routePrefix = $requested_slug.".";

//and I'm putting the data in the in the session
Session::put('lang_id', $lang->id);
Session::put('slug', $requested_slug);
Session::put('routePrefix', $routePrefix );
Session::put('lang', $lang->name);

And then I can write me routes using the requested slug as a prefix...

然后我可以使用请求的 slug 作为前缀来写我的路由......

Route::group(array('prefix' =>  $requested_slug), function()
{
    Route::get('/', function () {
        return "the language here is gonna be: ".Session::get('lang');
    });

    Route::resource('posts', 'PostsController');
    Route::resource('albums', 'AlbumsController');
});

This works but this code will ask the database for the languages everytime the route changes in my app. I don't know how I could, and if I should, figure out a mechanism that detects if the route changes to another language.

这是有效的,但是每次我的应用程序中的路线更改时,此代码都会向数据库询问语言。我不知道我怎么能,如果我应该,找出一种机制来检测路由是否更改为另一种语言。

Hope that helped.

希望有所帮助。