如何在 Laravel 视图中找到当前语言?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12706463/
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-09 02:20:28  来源:igfitidea点击:

How can I find the current language in a Laravel view?

localizationlaravel

提问by BenjaminRH

I'm using the Laravel Lang class for localization of my web app. I've added two languages to the languages array in application/config/application.php. This changes the default language it uses for localization to whatever the first part of the URI indicates (e.g. bla.com/en/bla and bla.com/co/bla). Now I need to be able to check what the current default language is in my view. However, the Lang class provides no way of checking this as far as I've been able to figure out, as the Lang::$languagevariable is protected. Is there any way of checking this apart from manually parsing the URI?

我正在使用 Laravel Lang 类来本地化我的网络应用程序。我已将两种语言添加到application/config/application.php. 这会将它用于本地化的默认语言更改为 URI 的第一部分所指示的任何内容(例如 bla.com/en/bla 和 bla.com/co/bla)。现在我需要能够检查我认为当前的默认语言是什么。但是,就我所知,Lang 类无法对此进行检查,因为该Lang::$language变量是受保护的。除了手动解析 URI 之外,还有什么方法可以检查这一点吗?

采纳答案by aebersold

BenjaminRH's answer is very good, and his suggested approach works perfectly. I've improved the snippet a bit. Now it detects the browser language and checks if that language is supported according to the application's config file.

BenjaminRH 的回答非常好,他建议的方法非常有效。我稍微改进了这个片段。现在它检测浏览器语言并根据应用程序的配置文件检查该语言是否受支持。

It's a quick hack, but it works on my app. Note that the application language is also set now. Feel free to use ore improve it.

这是一个快速的黑客,但它适用于我的应用程序。请注意,应用程序语言现在也已设置。随意使用矿石来改进它。

Route::filter('before', function()
{
    // current uri language ($lang_uri)
    $lang_uri = URI::segment(1);

    // Set default session language if none is set
    if(!Session::has('language'))
    {
        // use lang in uri, if provided
        if(in_array($lang_uri, Config::get('application.languages')))
        {
            $lang = $lang_uri;  
        }
        // detect browser language
        elseif(isset(Request::server('http_accept_language')))
        {
            $headerlang = substr(Request::server('http_accept_language'), 0, 2);

            if(in_array($headerlang, Config::get('application.languages')))
            {
                // browser lang is supported, use it
                $lang = $headerlang;
            }
            // use default application lang
            else
            {
                $lang = Config::get('application.language');
            }
        }
        // no lang in uri nor in browser. use default
        else 
        {
                // use default application lang
                $lang = Config::get('application.language');            
        }

        // set application language for that user
        Session::put('language', $lang);
        Config::set('application.language',  $lang);
    }
    // session is available
    else
    {
        // set application to session lang
        Config::set('application.language', Session::get('language'));
    }

    // prefix is missing? add it
    if(!in_array($lang_uri, Config::get('application.languages'))) 
    {
        return Redirect::to(URI::current());
    }
    // a valid prefix is there, but not the correct lang? change app lang
    elseif(in_array($lang_uri, Config::get('application.languages')) AND $lang_uri != Config::get('application.language'))
    {
        Session::put('language', $lang_uri);
        Config::set('application.language',  $lang_uri);    
    }
});

回答by Erwan

The cleanest way to know the current language of your website in Laravel appears to be :

在 Laravel 中了解网站当前语言的最简洁方法似乎是:

Lang::locale();

https://laravel.com/api/5.8/Illuminate/Translation/Translator.html#method_locale

https://laravel.com/api/5.8/Illuminate/Translation/Translator.html#method_locale

It's different than this command that will return the default language of your website :

它与此命令不同,它将返回您网站的默认语言:

Config::get('app.locale');

回答by Pedro Moreira

In the newer Laravel versions, you can get the current language with:

在较新的 Laravel 版本中,您可以通过以下方式获取当前语言:

Config::get('app.locale');

回答by ThatMSG

An alternative, a bit shorter way could be using something like this:

另一种更短的方法可能是使用这样的东西:

app()->getLocale()

The advantage of this is that IDEs such as PHPStorm recognize this function and can help you develop much faster.

这样做的好处是 PHPStorm 等 IDE 可以识别此功能,可以帮助您更快地开发。

回答by NIRAJ KUMAR

This would work fine

这会很好用

lang="{{ app()->getLocale() }}"

回答by BenjaminRH

I've figured out a solution to the language problem (thanks to nickstr on the IRC and the accepted answer to this question). It involves storing the current language as a session variable, which is updated when the language uri segment is changed.

我已经找到了语言问题的解决方案(感谢 IRC 上的 nickstr 以及对这个问题的公认答案)。它涉及将当前语言存储为会话变量,该变量在语言 uri 段更改时更新。

Route::filter('before', function()
{
    // Do stuff before every request to your application...

    // Default language ($lang) & current uri language ($lang_uri)
    $lang = 'he';
    $lang_uri = URI::segment(1);

    // Set default session language if none is set
    if(!Session::has('language'))
    {
        Session::put('language', $lang);
    }

    // Route language path if needed
    if($lang_uri !== 'en' && $lang_uri !== 'he')
    {
        Return Redirect::to($lang.'/'.URI::current());
    }
    // Set session language to uri
    elseif($lang_uri !== Session::get('language'))
    {
        Session::put('language', $lang_uri);
    }
});

回答by Johny Salas

This might help. Config::get('application.language')

这可能会有所帮助。配置::get('application.language')

回答by Sangar82

You can use

您可以使用

https://github.com/mcamara/laravel-localization

Laravel Localization uses the URL given for the request. In order to achieve this purpose, a group should be added into the routes.php file. It will filter all pages that must be localized.

Laravel 本地化使用为请求提供的 URL。为了达到这个目的,需要在 routes.php 文件中添加一个组。它将过滤所有必须本地化的页面。

    // app/routes.php

    Route::group(array('prefix' => LaravelLocalization::setLanguage()), function()
    {
        /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
        Route::get('/', function()
        {
            return View::make('hello');
        });

        Route::get('test',function(){
            return View::make('test');
        });
    });

    /** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/

Once this group is added to the routes file, an user can access to all languages added into the 'languagesAllowed' ('en' and 'es' for default, look at the config section to change that option). For example, an user can now access to two different languages, using the following addresses:

将此组添加到路由文件后,用户可以访问添加到“languagesAllowed”(默认为“en”和“es”,查看配置部分以更改该选项)的所有语言。例如,用户现在可以使用以下地址访问两种不同的语言:

http://laravel.com/en

http://laravel.com/en

http://laravel.com/es

http://laravel.com/es

http://laravel.com

http://laravel.com

回答by Thomas Venturini

I use App::getLocale()which is probably the most supported way as the App::setLocale('EN')method is used in the documentation.

我使用App::getLocale()的可能是最受支持的方式,因为文档中App::setLocale('EN')使用了该方法。

You can use this method everywhere. If it throughs an error somewhere, you can use \App::...to make it work.

您可以在任何地方使用此方法。如果它在某处发生错误,您可以使用\App::...它来使其工作。

I'm using Laravel 5.0.

我正在使用 Laravel 5.0。

回答by David Barker

The Langclass is specifically for outputting the correct language and as you say manages the language internally.

Lang班是专门为输出正确的语言,正如你说的在内部管理的语言。

Looking through the API there is no method to help you directly with this and parsing the URI to get the language would seem the appropriate course of action.

查看 API,没有任何方法可以直接帮助您解决这个问题,解析 URI 以获取语言似乎是适当的行动方案。

You can always just do this to retrieve the language string in the URI:

您总是可以这样做来检索 URI 中的语言字符串:

$language = URI::segment(1);

Examining Laravel Requests

检查 Laravel 请求