laravel 4 多语言网站
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14793008/
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
laravel 4 multilanguage website
提问by Flash-Square
I'm trying to implement a multilanguage laravel 4 website, with language code in the url ( mywebsite.com/en/home and mywebsite.com/de/home )
我正在尝试实现一个多语言 laravel 4 网站,网址中包含语言代码( mywebsite.com/en/home 和 mywebsite.com/de/home )
I've seen a couple of options like filtering all requests and checking if the first param is one of the language code.
我已经看到了几个选项,例如过滤所有请求并检查第一个参数是否是语言代码之一。
I've also check on packagist but haven't find something that already do tee job.
我也检查过 packagist,但还没有找到已经在做 T 恤工作的东西。
Is there a better way to implement it?
有没有更好的方法来实现它?
Thank you
谢谢
回答by Flash-Square
Finally, I've create a config variable in config/app.php
最后,我在 config/app.php 中创建了一个配置变量
'available_language' => array('en', 'fr', 'es'),
In filters.php I detect the browser language:
在filters.php中,我检测浏览器语言:
Route::filter('detectLang', function($lang = "auto")
{
if($lang != "auto" && in_array($lang , Config::get('app.available_language')))
{
Config::set('app.locale', $lang);
}else{
$browser_lang = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? strtok(strip_tags($_SERVER['HTTP_ACCEPT_LANGUAGE']), ',') : '';
$browser_lang = substr($browser_lang, 0,2);
$userLang = (in_array($browser_lang, Config::get('app.available_language'))) ? $browser_lang : Config::get('app.locale');
Config::set('app.locale', $userLang);
}
});
and then in routes.php I can either detect the language or force it:
然后在 routes.php 中,我可以检测语言或强制使用它:
Route::get('/', array(
'before' => 'detectLang()', // auto-detect language
function(){
...
})
);
or
或者
Route::get('/', array(
'before' => 'detectLang("fr")', // force language to "fe"
function(){
...
})
);
回答by Laurence
You could set a language variable in the user session.
您可以在用户会话中设置语言变量。
Then use a 'before
' filter, and view that variable, and log the correct language file.
然后使用“ before
”过滤器,查看该变量,并记录正确的语言文件。
If there is no variable set - then use a default (perhaps based upon their IP location).
如果没有设置变量 - 则使用默认值(可能基于其 IP 位置)。