Pergunta

Eu estou usando o Laravel de localização para fornecer duas línguas diferentes.Eu tenho todos o caminho coisas configurar, e mydomain.com/en/bla entrega em inglês e armazena o 'pt' variável de sessão, e mydomain.com/he/bla oferece hebraico e armazena o 'ele' variável de sessão.No entanto, eu não consigo descobrir uma maneira decente para proporcionar uma mudança de idioma link.Como seria esse trabalho?

Foi útil?

Solução

Eu já resolveu o meu problema adicionando este antes de filtro 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);

Outras dicas

Este é um post que eu postei originalmente no laravel fóruns, mas talvez possa ajudar alguém, então eu posto aqui também.

Eu tive alguns problemas com a construção de uma linguagem fácil switcher para o meu aplicativo e as informações sobre os fóruns, onde um pouco antigos (alguns cargos), então eu fiz esse simples pedaço de código que o torna supereasy para mudar o idioma do seu aplicativo na mosca.

Eu tenho as cadeias de idioma em meu ponto de vista, como a seguir:

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

E eu fico línguas com um URL, acho que esse é o melhor caminho, também o seu bom para o seo e links que as pessoas compartilham.Exemplo:

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

Ok, então o problema era que eu queria uma maneira fácil de alterar o idioma na hora, sem ter que mexer com sessões e cookies.Aqui está como eu fiz:

Fazer uma biblioteca em sua pasta de bibliotecas chamado chooselang.php

Insira este código dentro:

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

}

Após isso, você está pronto para começar seus url switcher URL:s gerados.Basta adicioná-los como você whould qualquer outra Lâmina links.

Exemplo de como gerar links para o finlandês, sueco e inglês (com Lâmina)

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

Acima irá gerar URL:s que estão sempre na página atual, e alterar o idioma slug para o que você deseja.Desta forma, as alterações de idioma para o que você quer, e o usuário naturalmente permanece na mesma página.O idioma padrão slug nunca é adicionado à url.

Gerado urls parecem algo como:

<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.Os links são especialmente úteis se você adicioná-los ao seu principal arquivo de modelo.

Você pode ter uma Rota de mão de mudança de linguagem, por exemplo:

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

Em seguida, no set ação no translator controlador poderia alterar a sessão, dependendo do idioma de código passados via URL.

Você também poderá alterar o parâmetro de configuração usando

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

Exemplo de controlador - translate.php

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

Apenas no caso de futuros usuários Se você quiser usar o pacote para localização, há um ótimo pacote em https://github.com/mcamara/laravel-localization .que é fácil de instalar e tem muitos ajudantes.

Esta pergunta ainda vem na pesquisa do Google, então aqui está a resposta se você estiver usando o Laravel 4 ou 5, e 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>

OBSERVE que este exemplo mostra bandeiras (em público/img/flags/{{locale}}.gif), e para usá-lo você vai precisar de um pouco de .o css, mas você pode modificá-lo para exibir o texto, se você quiser...

FYI.O mcamara/laravellocalization documentação tem exemplos e um MONTE de ajudantes, para olhar através da documentação no github.(https://github.com/mcamara/laravel-localization)

Tente usar a Sessão.Algo como isto:

Controlador:

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

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top