Laravelで言語を切り替えるための最良のロジックは何ですか?
-
13-12-2019 - |
質問
Laravel ローカリゼーションを使用して 2 つの異なる言語を提供しています。すべてのパスの設定が完了しました。mydomain.com/en/bla は英語を配信し、「en」セッション変数を保存します。mydomain.com/he/bla はヘブライ語を配信し、「he」セッション変数を保存します。ただし、言語切り替えリンクを提供する適切な方法がわかりません。これはどのように機能しますか?
解決
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);
. 他のヒント
これは私が最初にLarvelフォーラムに投稿された投稿ですが、それは他の誰かを助けるでしょう、それで私もここに投稿します。
私のアプリのための簡単な言語スイッチャーを構築することにいくつかの問題を抱えていました、そしてちょっとした古い(いくつかの投稿)が、私はあなたの言語を変更することを使い果たすようなこの単純なコードを作りました。飛ぶアプリ。
私のビューに言語文字列を以下のように持っています:
{{ __('languagefile.the_language_string'); }}
.
そして私はURLを使って言語を手に入れます、私はこれが最善の方法であり、SEOにとっても、人々が共有するリンクのためにも良いことです。例:
www.myapp.com/fi/support (Finnish)
www.myapp.com/en/support (English)
www.myapp.com/sv/support (Swedish)
.
OK、その問題は、セッションやクッキーを台無しにすることなく、その場で言語を変更する簡単な方法を望んでいたということでした。私がそれを作った方法:
ライブラリーのライブラリを作成します。 chooselang.php
という名前のフォルダこのコードを内部に挿入します。
class Chooselang extends HTML {
/**
* Generate a Language changer link.
*
* <code>
* // Generate a link to the current location,
* // but still change the site langauge on the fly
* // Change $langcode to desired language, also change the Config::set('application.language', 'YOUR-LANG-HERE')); to desired language
* // Example
* echo Chooselang::langslug(URI::current() , $langcode = 'Finnish' . Config::set('application.language', 'fi'));
* </code>
*
* @param string $url
* @param string $langcode
* @param array $attributes
* @param bool $https
* @return string
*/
public static function langslug($url, $langcode = null, $attributes = array(), $https = null)
{
$url = URL::to($url, $https);
if (is_null($langcode)) $langcode = $url;
return '<a href="'.$url.'"'.static::attributes($attributes).'>'.static::entities($langcode).'</a>';
}
}
.
これ以降、URLスイッチャーのURLを取得する準備が整いました。他のブレードリンクがあるとするだけでそれらを追加するだけです。
例フィンランド語、スウェーデン語、英語のリンクを生成する方法
{{ Chooselang::langslug(URI::current() , $langcode = 'Fin' . Config::set('application.language', 'fi')); }}
{{ Chooselang::langslug(URI::current() , $langcode = 'Swe' . Config::set('application.language', 'sv')); }}
{{ Chooselang::langslug(URI::current() , $langcode = 'Eng' . Config::set('application.language', 'en')); }}
.
上記では、常に現在のページにあるURLを生成し、必要なものを望むものに変更します。このようにして言語があなたが望むものに変わり、ユーザーは自然に同じページに留まります。デフォルトの言語スラッグはURLに追加されません。
生成されたURLのように見える:
<a href="http://localhost/laravel/public/support">Fin</a>
<a href="http://localhost/laravel/public/sv/support">Swe</a>
<a href="http://localhost/laravel/public/en/support">Eng</a>
.
ps。リンクは、マスターテンプレートファイルに追加した場合に特別に便利です。 たとえば、ルートから言語を変更することもできます。
Route::get('translate/(:any)', 'translator@set');
それから、 set
でのアクション translator
コントローラーは、URL 経由で渡された言語コードに応じてセッションを変更する可能性があります。
次を使用して構成設定を変更することもできます。
Config::set('application.language', $url_variable');
コントローラーの例 - translation.php
public function action_set($url_variable)
{
/* Your code Here */
}
将来のユーザーの場合は、ローカライズのためにパッケージを使用したい場合は、 httpsに素晴らしいパッケージがあります。//github.com/mcamara/laravel-localization 。インストールが簡単で、多くのヘルパーがあります。
この質問はまだGoogle検索に入っているので、Laravel 4または5、Mcamara / Laravellicationを使用している場合は、ここに答えがあります。
<ul>
<li class="h5"><strong><span class="ee-text-dark">{{ trans('common.chooselanguage') }}:</span></strong> </li>
@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
<li>
<a rel="alternate" hreflang="{{$localeCode}}" href="{{LaravelLocalization::getLocalizedURL($localeCode) }}">
<img src="/img/flags/{{$localeCode}}.gif" /> {{{ $properties['native'] }}}
</a>
</li>
@endforeach
</ul>
.
この例ではフラグを示しています(public / img / flags / {{locale}}} .GIF)、それを使用することはちょっと.cssが必要ですが、それを変更してテキストを表示してテキストを表示してテキストを表示してテキストを表示することができます。欲しい...
FYI。Mcamara / Laravellocalizationのマニュアルには、例と多くのヘルパーがありますので、GitHubのドキュメントを見てください。( https://github.com/mcamara/laravel-localization )
セッションを使用してみてください。このような何か:
コントローラ:
class Language_Controller extends Base_Controller {
function __construct(){
$this->action_set();
parent::__construct();
}
private function checkLang($lang = null){
if(isset($lang)){
foreach($this->_Langs as $k => $v){
if(strcmp($lang, $k) == 0) $Check = true;
}
}
return isset($Check) ? $Check : false;
}
public function action_set($lang = null){
if(isset($lang) && $this->checkLang($lang)){
Session::put('lang', $lang);
$this->_Langs['current'] = $lang;
Config::set('application.language', $lang);
} else {
if(Session::has('lang')){
Config::set('application.language', Session::get('lang'));
$this->_Langs['current'] = Session::get('lang');
} else {
$this->_Langs['current'] = $this->_Default;
}
}
return Redirect::to('/');
}
}
.
worles.php:
Route::get('lang/(:any)', 'language@set');
. I've been doing it like this:
$languages = Config::get('lang.languages'); //returns array('hrv', 'eng')
$locale = Request::segment(1); //fetches first URI segment
//for default language ('hrv') set $locale prefix to "", otherwise set it to lang prefix
if (in_array($locale, $languages) && $locale != 'hrv') {
App::setLocale($locale);
} else {
App::setLocale('hrv');
$locale = null;
}
// "/" routes will be default language routes, and "/$prefix" routes will be routes for all other languages
Route::group(array('prefix' => $locale), function() {
//my routes here
});
Source: http://forumsarchive.laravel.io/viewtopic.php?pid=35185#p35185
What I'm doing consists of two steps: I'm creating a languages table which consists of these fields:
id | name | slug
which hold the data im gonna need for the languages for example
1 | greek | gr
2 | english | en
3 | deutch | de
The Language model I use in the code below refers to that table.
So, in my routes.php I have something like:
//get the first segment of the url
$slug = Request::segment(1);
$requested_slug = "";
//I retrieve the recordset from the languages table that has as a slug the first url segment of request
$lang = Language::where('slug', '=', $slug)->first();
//if it's null, the language I will retrieve a new recordset with my default language
$lang ? $requested_slug = $slug : $lang = Language::where('slug', '=', **mydefaultlanguage**')->first();
//I'm preparing the $routePrefix variable, which will help me with my forms
$requested_slug == ""? $routePrefix = "" : $routePrefix = $requested_slug.".";
//and I'm putting the data in the in the session
Session::put('lang_id', $lang->id);
Session::put('slug', $requested_slug);
Session::put('routePrefix', $routePrefix );
Session::put('lang', $lang->name);
And then I can write me routes using the requested slug as a prefix...
Route::group(array('prefix' => $requested_slug), function()
{
Route::get('/', function () {
return "the language here is gonna be: ".Session::get('lang');
});
Route::resource('posts', 'PostsController');
Route::resource('albums', 'AlbumsController');
});
This works but this code will ask the database for the languages everytime the route changes in my app. I don't know how I could, and if I should, figure out a mechanism that detects if the route changes to another language.
Hope that helped.