在多语言网站中生成链接

时间:2018-06-21 11:15:43

标签: php laravel cookies middleware multilingual

我有多国语言网站。为了对网站进行语言环境设置,我使用了如下中间件:

public function handle($request, Closure $next)
{
    App::setlocale('pl');
    Cookie::queue(Cookie::make('lang', 'pl'), true, 1440);
    return $next($request);
}

我的roote名称如下:“ pl.articles”或“ en.acritcles”,因此我使用Cookie生成了视图链接。例如:

@if(Cookie::get('lang') == 'pl')
    <li><a href="{{ route('pl.allwomens') }}">@lang('category.womens')</a></li>
@else
  <li><a href="{{ route('en.allwomens') }}">@lang('category.womens')</a></li>
@endif

可以,但是我有一点问题。当我更改语言时,确实会链接到旧版本。因此,我必须重新加载网站才能更改链接。有时,我单击某些链接后,我网站的语言就会改变。我再次单击,语言将回到以前的版本。问题出在哪里? 我在一组中使用中间件

Route::group(['prefix' => 'pl', 'middleware' => ['PLLanguage', 'globalStats']], function(){

1 个答案:

答案 0 :(得分:0)

创建称为“语言”的中间件

<?php namespace App\Http\Middleware;

use Closure, Session, Auth;

class SetLanguage {


    protected $languages = ['en','pl'];

    public function handle($request, Closure $next)
    {
        if(isset($request->applocale)){

            if(in_array($request->applocale, $this->languages)){
                if(!Session::has('locale'))
                { 
                    Session::put('locale', $request->applocale);

                } else if( Session::get('locale') != $request->applocale ){
                    Session::put('locale', $request->applocale);
                    app()->setLocale(Session::get('locale'));
                }
            }

            else abort(500, 'Bad request, requested language not found');

        }

        app()->setLocale(Session::get('locale'));

        return $next($request);
    }
}

将此中间件放入您的Web组的Kernel.php文件

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\SetLanguage::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

创建语言更改表格

<a href="#" onclick="setLanguage(event, 'en')">English</a>
<a href="#" onclick="setLanguage(event, 'pl')">ქართული</a>
<form action="/setlanguage" method="POST" style="display: none" id="languageForm">
    @csrf
    <input id="applocale" type="text" name="applocale" >
</form>
<script>
    function setLanguage(e, lang){
        e.preventDefault();
        $('#applocale').val(lang);
        $('#languageForm').submit();
    }
</script>

因此将在每个提交表单上设置语言

然后在您的视图中可以使用

@php $lang = app()->getLocale(); @endphp
<li><a href="{{ route($lang.'.allwomens') }}">@lang('category.womens')</a></li>