我安装了此软件包“ https://github.com/mcamara/laravel-localization”。
我想基于选择菜单来翻译站点,因此,当用户在选择菜单中选择一种语言时,应该使用上述软件包将站点内容翻译为所选语言。
但是它不起作用,当用户以以下形式更改语言时,下面的代码在RouteCollection.php中显示为“ Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException。
然后我上了这个课:
namespace App\Http\Middleware;
use Closure;
class Translate
{
protected $default = 'en';
protected $languages = [
'en',
'nl',
'fr',
];
public function handle($request, Closure $next)
{
if($request->has('language')) {
$lang = $request->language;
if(array_search($lang, $this->languages) === false) {
$lang = $this->default;
}
$request->session()->put('lang', $lang);
}
\LaravelLocalization::setLocale( $request->session()->get('lang') );
return $next($request);
}
}
在kernel.php中:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class, // <-- without this one, it wont work
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Translate::class, // <-- Add it here
],
'api' => [
'throttle:60,1',
'bindings',
],
];
然后用户的选择菜单更改语言:
form method="get" id="translate">
<select name="language" class="form-control font-weight-normal text-gray" id="language" onchange="localize">
<option value="en">English</option>
<option value="fr">French</option>
<option value="es">Spanish</option>
<option>5</option>
</select>
</form>
jQuery:
$(document).ready(function(){
var myFormName = "translate";
$('#language').on('change', function)(){
$('#translate).submit();
});
});