看了官方文檔薄腻,有點懵隐圾,結(jié)合自己摸索橄镜,記錄下多語言化這事兒在Laravel里怎么搞必指。
在~/config/app.php
文件中加入應(yīng)用支持的語言版本
'locales' => ['en' => 'English', 'cn' => 'Chinese', 'jp' => 'Japanese'],
同時 ~/config/app.php
里面還有一個fallback_locale
,可以在這里設(shè)定候補語言種類株茶,當(dāng)一個String在目標(biāo)語言中沒有時可以顯示在候補語言中的翻譯来涨。我們先設(shè)為
'fallback_locale' => 'en',
官方文檔里寫了用App::setLocale(); 這個方法,這里有個坑启盛,試了發(fā)現(xiàn)它是易揮發(fā)的 non-persistent 就是作用范圍僅僅是當(dāng)前這個request扫夜,你跳個頁面就沒了。
擦,看來只能自己動手了笤闯。思路是把當(dāng)前的語言設(shè)定存在Session里頭堕阔,然后再寫個Middleware去截Http請求,在截住的請求里用Session里的語言設(shè)定值來設(shè)Locale颗味。
第一步超陆,先創(chuàng)建個LanguageController,用來處理設(shè)置語言種類的請求
php artisan make:controller LanguageController
代碼如下
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LanguageController extends Controller
{
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function setLocale($lang){
if (array_key_exists($lang, config('app.locales'))) {
session(['applocale' => $lang]);
}
return back()->withInput();
}
}
第二步 改路由浦马,在routes\web.php
里面加個指向LanguageController@changeLanguage的路由时呀,如下
Route::get('lang/{locale}', ['as'=>'lang.change', 'uses'=>'LanguageController@setLocale']);
第三步 在前端頁面里頭放個選擇語言的鏈接列表,如下
@foreach (Config::get('app.locales') as $lang => $language)
@if ($lang != App::getLocale())
<li><a href="{{ route('lang.change', $lang) }}">{{$language}}</a></li>
@endif
@endforeach
第四步 做個Language的Middleware晶默,截住請求谨娜,改當(dāng)前Request的語言設(shè)定
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;
class Language
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Session::has('applocale') AND array_key_exists(Session::get('applocale'), Config::get('app.locales'))) {
App::setLocale(Session::get('applocale'));
}
else { // This is optional as Laravel will automatically set the fallback language if there is none specified
App::setLocale(Config::get('app.fallback_locale'));
}
return $next($request);
}
}
第五步 把Language這個中間件在Kernel.php里頭注冊好
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\Language::class, // Alex Globel Language Settings 2017-03-17
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
完工了