문제

나는 두 개의 다른 언어를 제공하기 위해 LARAVLE 현지화를 사용하고 있습니다.모든 경로가 설정되어 있으며 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 포럼에 게시 한 게시물이지만, 어쩌면 다른 사람을 도울 것입니다.

내 앱을위한 쉬운 언어 스위처를 구축하는 데 어려움을 겪었으며, 약간의 오래된 (일부 게시물) 포럼에 대한 정보가 있으므로이 간단한 코드를 만들어서 슈퍼 슈즈가 당신의 언어를 바꿀 수있게 만들었습니다. 플라이 앱.

다음과 같이 내 견해에 언어 문자열이 있습니다 :

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

및 나는 언어를 URL로 얻습니다. 나는 이것이 가장 좋은 방법이라고 생각합니다. 또한 SEO와 사람들이 공유하는 링크를 위해 예 :

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

OK, 그래서 문제는 세션과 쿠키를 어지럽히지 않고 비행기에서 언어를 바꿀 수있는 쉬운 방법을 원했습니다. 내가 어떻게 만든지 heres :

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을 생성하고 항상 현재 페이지에있는 URL을 생성하고 원하는 랭글러를 변경합니다. 이러한 방식으로 언어가 원하는 것을 변경하고 사용자는 자연스럽게 동일한 페이지에 머물러 있습니다. 기본 언어 슬러그는 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 컨트롤러의 The URL을 통해 전달 된 언어 코드에 따라 세션을 변경할 수 있습니다.

를 사용하여 구성 설정을 변경할 수도 있습니다.

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

컨트롤러 예 - translate.php

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

향후 사용자가 현지화 패키지를 사용하려면 https : https ://github.com/mcamara/laravel-localization .설치가 쉽고 많은 도우미가 있습니다.

이 질문은 여전히 Google 검색에서 제공되므로 Laravel 4 또는 5 및 Mcamara / Lalavellocalization을 사용하는 경우 여기에 답변이 있습니다.

<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 / {{{locale}}). GIF)를 보여주고 사용하는 것은 .css가 약간의 .css가 필요하지만 텍스트를 표시 할 수 있도록 수정할 수 있습니다.원한다 ...

fyi.Mcamara / Laravellocalization 문서에는 예제와 많은 도우미가 있으므로 GitHub에 대한 문서를 살펴보십시오.( "nofollization"> https://github.com/mcamara/laravel-localization )

세션을 사용하십시오.이렇게 같은 somthing :

컨트롤러 :

 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