如何在Laravel中进行多语言(本地化)? [英] how to make multilingual (localization) in Laravel?

查看:92
本文介绍了如何在Laravel中进行多语言(本地化)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在laravel中创建本地化,并在laravel官方文档中给出了本地化,它的工作原理很吸引人!!但是,它仅适用于单个请求.我希望它能满足所有请求,直到用户更改语言为止. 如何不仅在laravel文档中给出的单个请求中,在laravel中创建多语言站点?

I have tried to create localization in laravel as well as given in laravel official documentation and it worked like charm!! However it works only for single request. I want it to work for all requests until user changes language. how to create multilingual site in laravel not only for single request as given in laravel documentation?

推荐答案

首先,我们需要编写一些锚标记(在您的home.blade.php页面中使用您的锚标记)来切换如下所示的语言...

First of all we need to write few anchor tags (use yours: in your home.blade.php page) to switch language like below...

    <a href="{{url('change/locale/en')}}">ENGLISH</a>
    <a href="{{url('change/locale/fr')}}">FRENCH</a>
    <a href="{{url('change/locale/uz')}}">UZBEK</a>

然后我们需要创建如下所示的Route来接受请求...

then we need to create following Route like below to accept requests...

    Route::get('change/locale/{lang}', function($lang){
        Session::put('locale', $lang);
        return redirect()->back();
    });

下一步是在终端中运行此命令以创建名为LanguageMiddleware

next step is to run this command in your terminal to create middleware named LanguageMiddleware

    php artisan make:middleware LanguageMiddleware

之后,打开我们在app/Http/Middleware文件夹中创建的LanguageMiddleware,并将这对代码替换为handle方法

after that lets open our LanguageMiddleware that we created into app/Http/Middleware folder and replace this couple of code with handle method

public function handle($request, Closure $next)
{
    if ( Session::has('locale')) {
        App::setLocale(Session::get('locale'));
    }
    return $next($request);
}

现在添加此行

\App\Http\Middleware\LanguageMiddleware::class

进入Kernel.php -> protected $middlewareGroups -> web

并创建名为 enuzfr放入views/lang文件夹. 然后在我们在(en,fr,uz)

and create folders called en , uz , fr into views/lang folder. then create messages.php file in every folder we created above (en,fr,uz)

现在您的文件夹必须看起来像这样.

now your folders must look just like this.

现在您可以像这样调用字典

now you can call your dictionary like this

@lang('messages.greeting')

那就结束了!现在,您可以通过单击我们在第一步中创建的锚标签来对其进行检查.

that's end ! now you can check it by clicking on your anchor tags that we created in first step.

这篇关于如何在Laravel中进行多语言(本地化)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆