在 Laravel 中切换语言的最佳逻辑是什么?

2022-01-11 00:00:00 localization php laravel

我正在使用 Laravel 本地化来提供两种不同的语言.我已经设置了所有路径,mydomain.com/en/bla 提供英语并存储en"会话变量,mydomain.com/he/bla 提供希伯来语并存储he"会话变量.但是,我想不出一种体面的方式来提供语言切换链接.这将如何运作?

I'm using Laravel localization to provide two different languages. I've got all the path stuff set up, and mydomain.com/en/bla delivers English and stores the 'en' session variable, and mydomain.com/he/bla delivers Hebrew and stores the 'he' session variable. However, I can't figure out a decent way to provide a language-switching link. How would this work?

推荐答案

我已经通过将这个添加到 routes.php 中的 before 过滤器解决了我的问题:

I've solved my problem by adding this to the before filter in routes.php:

// 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.'/'.($lang_uri ? URI::current() : ''));
}
// Set session language to uri
elseif($lang_uri !== Session::get('language'))
{
    Session::put('language', $lang_uri);
}

// Store the language switch links to the session
$he2en = preg_replace('/he//', 'en/', URI::full(), 1);
$en2he = preg_replace('/en//', 'he/', URI::full(), 1);
Session::put('he2en', $he2en);
Session::put('en2he', $en2he);

相关文章