如何在 Laravel 5.3 中获取当前语言环境

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41506076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:35:59  来源:igfitidea点击:

How to fetch current locale in view in Laravel 5.3

laravellaravel-5.3bladelaravel-blade

提问by Fahad Iqbal Ahmad Khan

I am making a bilingual app. I am using same routes for each but I am using different views for both languages. Whenever I want to redirect to a route I want to pass {{ route('test.route', 'en') }}. Where I am passing en, I want to fetch the current locale value from the view and then pass it to the route. Please help.

我正在制作一个双语应用程序。我对每个都使用相同的路线,但我对两种语言使用不同的视图。每当我想重定向到我想通过的路线时{{ route('test.route', 'en') }}。在我传递的地方en,我想从视图中获取当前的语言环境值,然后将其传递给路由。请帮忙。

回答by Arun Code

try this. It will give the locale set in your application

尝试这个。它将提供在您的应用程序中设置的语言环境

Config::get('app.locale')

Edit:

编辑:

To use this in blade, use like the following, to echo your current locale in blade.

要在刀片中使用它,请使用如下所示,以在刀片中回显您当前的语言环境。

{{ Config::get('app.locale') }}

If you want to do a if condition in blade around it, it will become,

如果你想在它周围的刀片中做一个 if 条件,它会变成,

   @if ( Config::get('app.locale') == 'en')

   {{ 'Current Language is English' }}

   @elseif ( Config::get('app.locale') == 'ru' )

   {{ 'Current Language is Russian' }}

   @endif

To get current locale,

要获取当前语言环境,

app()->getLocale()

回答by rashedcs

At first create a locale route and controller :

首先创建一个区域设置路由和控制器:

Route::get('/locale/{lang}', 'LocaleController@setLocale')->name('locale');

class LocaleController extends Controller
{
    public function setLocale($locale)
    {
        if (array_key_exists($locale, Config::get('languages'))) 
        {
            Session::put('app_locale', $locale);
        }
        return redirect()->back();
    }
}

Now you can check easily in every page:

现在您可以在每个页面中轻松查看:

  $locale = app()->getLocale();
  $version = $locale == 'en' ? $locale . 'English' : 'Bangla';