如何在Laravel 5中检测语言偏好 [英] How to detect language preference in Laravel 5
问题描述
我想通过获取浏览器推荐的语言来检测客户端语言.
I want to detect my client language by getting the browser recommended language.
例如,如果您在日本打开浏览器,则会向我提供当前打开的用户的国家代码或国家名称,例如"en-jp"或"japan".
For Example, if you open the browser in Japan it will give me country code or country name current user opened like "en-jp" or "japan".
我尝试使用此代码,但它似乎显示了我先前选择的语言,默认情况下为英语.
I try this code but it seems to display the language that I previously selected and by default it's English.
我设置了一个中间件,并且需要排除api部分,因为我有一些路由器ping该地址,并且路由器浏览器没有语言信息,这会阻塞系统.
I set a Middleware and I need to exclude the api part because I have some routers pinging this address and router browser does not have language information which brick the system.
class BeforeMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
protected $except_urls = [
'api/*'
];
public function handle($request, Closure $next)
{
$langArr = array("en", "fr");
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
} else {
$languages[0] = "en";
}
if (Session::has('locale')) {
App::setLocale(Session::get('locale'));
} else {
if (in_array($languages[0], $langArr))
App::setLocale($languages[0]);
}
return $next($request);
}
} /* end class */
感谢您的帮助.
推荐答案
要简单地从标题中获取语言环境,可以从请求中获取http-accept-language
值.这可以通过外观访问,也可以在中间件中使用request变量:
To simply get the locale from the header, you can grab the http-accept-language
value from the request. This is accessible via a facade or you can use the request variable in your middleware:
Request::server('HTTP_ACCEPT_LANGUAGE')
// OR
$request->server('HTTP_ACCEPT_LANGUAGE');
这将返回一个类似于以下内容的字符串:en-GB,en;q=0.8
.然后,您可以解析它(也许使用explode()
?)并从那里获取语言.
This returns a string which looks like this: en-GB,en;q=0.8
. You can then parse it (perhaps using explode()
?) and grab the language from there.
但是,这种事情有时会变得复杂.如果您需要做更高级的事情,有一个软件包可以为您完成所有这些工作:
However, this sort of thing can sometimes get complicated. If you need to do something more advanced, there's a package which can do all of this for you:
https://github.com/mcamara/laravel-localization
这篇关于如何在Laravel 5中检测语言偏好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!