What's the best logic for switching language i

2020-02-16 07:17发布

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?

8条回答
▲ chillily
2楼-- · 2020-02-16 07:38

This question still comes in Google search, so here's the answer if you're using Laravel 4 or 5, and 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...

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)

查看更多
小情绪 Triste *
3楼-- · 2020-02-16 07:40

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

查看更多
倾城 Initia
4楼-- · 2020-02-16 07:43

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

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

Then in the set action in the translator controller could alter the session, depending on the language code passed via the URL.

You could also alter the configuration setting by using

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

Controller Example - translate.php

public function action_set($url_variable)
{
     /* Your code Here */
}
查看更多
smile是对你的礼貌
5楼-- · 2020-02-16 07:46

Try use Session's. Somthing like this:

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::get('lang/(:any)', 'language@set');
查看更多
迷人小祖宗
6楼-- · 2020-02-16 07:47

I've solved my problem by adding this to the before filter in 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);
查看更多
Rolldiameter
7楼-- · 2020-02-16 07:54

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.

查看更多
登录 后发表回答