首页 文章

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

提问于
浏览
29

我正在使用Laravel本地化来提供两种不同的语言 . 我已经设置了所有路径,mydomain.com/en/bla提供英语并存储'en'会话变量,mydomain.com/he/bla提供希伯来语并存储'他'会话变量 . 但是,我无法找到一种提供语言切换链接的好方法 . 这怎么样?

8 回答

  • 1

    我已经通过将其添加到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);
    
  • 1

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

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

    我在视图中有以下语言字符串:

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

    我使用URL获取语言,我认为这是最好的方式,也适用于seo和人们共享的链接 . 例:

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

    好吧,问题是我想要一种简单的方法来动态更改语言,而不必乱搞会话和cookie . 继承人我是怎么做到的:

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

    在此处插入此代码:

    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>';
        }
    
    }
    

    在此之后,您就可以获取生成的URL切换器URL了 . 只需添加它们就像任何其他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')); }}
    

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

    生成的URL看起来像:

    <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 . 如果将链接添加到主模板文件中,则链接特别有用 .

  • 12

    您可以使用Route to hand语言更改,例如:

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

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

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

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

    Controller Example - translate.php

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

    以防万一未来的用户如果你想使用软件包进行本地化,那么https://github.com/mcamara/laravel-localization就有一个很棒的软件包 . 这很容易安装,并有很多帮手 .

  • 14

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

    控制器:

    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('/');
        }
    }
    

    在Route.php中:

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

    我一直在这样做:

    $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
    
    });
    

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

  • 5

    这个问题仍然存在于谷歌搜索中,所以如果您使用的是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>
    

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

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

  • 0

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

    id |名字|金属块

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

    1 |希腊| GR

    2 |英语|恩

    3 | deutch |德

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

    所以,在我的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);
    

    然后我可以使用请求的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');
    });
    

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

    希望有所帮助 .

相关问题