我正在使用Laravel本地化来提供两种不同的语言。我已经设置了所有的路径,而mydomain.com/en/bla一起提供英语并存储“en”会话变量,而mydomain.com/he/bla提供希伯来语并存储“他”的会话变量。但是,我无法弄清楚提供语言切换链路的体面方式。这是怎么回事?

有帮助吗?

解决方案

我通过将其添加到routes.php:

中的过滤器来解决问题
// 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);
.

其他提示

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

我对我的应用程序构建一个简单的语言切换器,以及论坛的信息有些麻烦,有点旧的(一些帖子),所以我制作了这个简单的代码,使其成为改变语言的超级代码app在飞行。

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

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

我用网址获得语言,我认为这是最好的方法,它对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:s生成。只要将任何其他刀片链接添加它们即可添加它们。

如何生成芬兰语,瑞典语和英语(带刀片)的链接

  {{ 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更改为您想要的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。如果将它们添加到主模板文件中,链接是特别有用的。

您可以进行手动语言更改的路由,例如:

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

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

您还可以使用

更改配置设置

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

控制器示例 - translate.php

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

如果要为未来的用户,如果要使用包装包,则在 https://github.com/mcamara/laravel -localization 。这很易于安装并有很多帮助者。

这个问题仍然来自谷歌搜索,所以如果你使用的是你使用的laravel 4或5,以及mcamara / laravellcalization是答案。

<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>
.

请注意,此示例显示标志(公共/ img / flags / {{locale}}。gif),并使用它需要一点.css,但如果您可以修改它以显示文本想要...

fyi。Mcamara / LaravellCalization文档有示例和很多帮助者,所以通过GitHub上的文档看。( https://github.com/mcamara/laravel -localization

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

控制器:

 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');
.

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

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

2 | english | en

3 | deutch | de

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

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

//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...

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top