Laravel¿ª·¢£ºÔõÑùʹÓÃLaravel LocalizationʵÏÖ¶àÓïÑÔÖ§³Ö£¿
Ëæ×ÅÈ«Çò»¯µÄÇ÷ÊÆ£¬Ô½À´Ô½¶àµÄÍøÕ¾ºÍÓ¦ÓóÌÐòÐèÒªÖ§³Ö¶àÖÖÓïÑÔ¡£ÔڹŰåµÄÍøÕ¾¿ª·¢ÖУ¬Í¨³£ÐèÒªÊÖ¶¯¹¹½¨¶à¸öÓïÑÔ°æ±¾µÄÒ³Ã棬Õâ²»µ«ºÄʱºÄÁ¦£¬²¢ÇÒÈÝÒ×ÍÉ»¯¡£Ëæ×ÅÏÖ´ú¿ª·¢ÊÖÒÕµÄÉú³¤£¬Ê¹Óÿò¼ÜºÍ¹¤¾ßÀ´¼ò»¯¶àÓïÑÔÖ§³ÖÒѾ³ÉΪһÖÖÇ÷ÊÆ¡£
ÔÚLaravel¿ª·¢ÖУ¬Laravel LocalizationÊÇÒ»ÖÖÊ¢Ðеķ½·¨À´ÊµÏÖ¶àÓïÑÔÖ§³Ö¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃLaravel LocalizationÀ´ÔÚLaravelÓ¦ÓóÌÐòÖÐʵÏÖ¶àÓïÑÔÖ§³Ö¡£
×°ÖúÍÉèÖÃ
Ê×ÏÈ£¬ÐèҪװÖÃlaravelµÄÍâµØ»¯×é¼þ¡£¿ÉÒÔʹÓÃcomposerÀ´×°Öãº
composer require "laravelcollective/html":"^5.8.0" php artisan vendor:publish --tag=laravel-errors --force
µÇ¼ºó¸´ÖÆ
È»ºó£¬ÐèÒªÔÚapp/configÏÂн¨Îļþlocale.php£¬ÓÃÓÚÉèÖÃÖ§³ÖµÄÓïÑÔÑ¡Ï
return [ 'locales' => ['en' => 'English', 'zh' => 'ÖÐÎÄ'], 'default_locale' => 'en' ];
µÇ¼ºó¸´ÖÆ
ÔÚÕâÀlocalesÊý×é°üÀ¨ÁËËùÖ§³ÖµÄÓïÑÔÑ¡ÏÆäÖÐÿ¸öÔªËصļüÊÇÓïÑԵĴúÂ룬ֵÊÇÓïÑÔµÄÃû³Æ¡£default_localeÖ¸¶¨Ä¬ÈϵÄÓïÑÔÑ¡Ïî¡£
½¨Éè¶àÓïÑÔ×ÊÔ´
½ÓÏÂÀ´£¬ÐèҪΪËùÖ§³ÖµÄÿÖÖÓïÑÔ½¨ÉèÏìÓ¦µÄÓïÑÔ×ÊÔ´Îļþ¡£ÓïÑÔ×ÊÔ´Îļþͨ³£°üÀ¨Ò»¸öÊý×飬ÆäÖаüÀ¨ÔÚ¸ÃÓïÑÔÇéÐÎÏÂʹÓõÄËùÓÐÍâµØ»¯×Ö·û´®¡£¿ÉÒÔʹÓÃartisanÏÂÁîÀ´¿ìËÙ½¨ÉèÕâЩÎļþ£¬ÈçÏÂËùʾ£º
php artisan make:lang en php artisan make:lang zh
µÇ¼ºó¸´ÖÆ
Õ⽫½¨ÉèÁ½¸ölangĿ¼£¬Ò»¸öÊÇÓ¢ÎÄ£¬Ò»¸öÊÇÖÐÎÄ¡£
±à¼¶àÓïÑÔ×ÊÔ´
±à¼Ã¿¸öÓïÑÔÇéÐεÄÓïÑÔ×ÊÔ´Îļþ£¬½«Ìض¨ÓÚ¸ÃÓïÑÔÇéÐεÄÍâµØ»¯×Ö·û´®Ìí¼Óµ½Êý×éÖС£ÀýÈ磬ÔÚen.phpºÍzh.phpÎļþÖУ¬¿ÉÒÔÌí¼ÓÒÔÏÂÄÚÈÝ£º
// en.php return [ "welcome" => "Welcome to our site", "about" => "About Us", "contact" => "Contact Us" ]; // zh.php return [ "welcome" => "½Ó´ý»á¼ûÎÒÃǵÄÍøÕ¾", "about" => "¹ØÓÚ尊龙凯时人生就是博", "contact" => "ÁªÏµ尊龙凯时人生就是博" ];
µÇ¼ºó¸´ÖÆ
ÔÚÊÓͼÖÐʹÓÃÍâµØ»¯×Ö·û´®
µ±ÊÓͼÐèÒª°üÀ¨ÍâµØ»¯×Ö·û´®Ê±£¬¿ÉÒÔʹÓÃLaravel LocalizationÖÐÌṩµÄtransº¯Êý¡£transº¯Êý½ÓÊÜÒ»¸öÍâµØ»¯×Ö·û´®µÄ¼ü£¬²¢·µ»ØÏìÓ¦µÄÍâµØ»¯×Ö·û´®¡£ÀýÈ磬ÔÚbladeÄ£°åÖУ¬¿ÉÒÔÕâÑùʹÓÃtransº¯Êý£º
<h1>{{ trans('messages.welcome') }}</h1>
µÇ¼ºó¸´ÖÆ
ÔÚÕâÀtransº¯Êý½«Æ¾Ö¤Ä¿½ñÓïÑÔÇéÐηµ»ØÏìÓ¦µÄÍâµØ»¯×Ö·û´®¡£
Çл»ÓïÑÔÑ¡Ïî
×îºó£¬»¹¿ÉÒÔÔÚÓ¦ÓóÌÐòÖÐÌṩÇл»ÓïÑÔÑ¡ÏîµÄ¹¦Ð§¡£¿ÉÒÔÔÚÊÓͼÖн¨ÉèÒ»¸öÏÂÀ¿òÀÍÆÈ´»ÓïÑÔÑ¡Ï²¢Ê¹ÓÃJavaScriptÀ´Ìá½»±íµ¥£¬ÒԱ㽫ѡÔñµÄÓïÑÔÑ¡ÏîÉúÑĵ½LaravelµÄSessionÖС£
<form id="locale-form" method="POST" action="{{ url('locale') }}"> {{ csrf_field() }} <select name="locale" onchange="document.querySelector('#locale-form').submit();"> @foreach (Config::get('locale.locales') as $key => $value) <option value="{{ $key }}" {{ ($key === App::getLocale()) ? ' selected' : '' }}>{{ $value }}</option> @endforeach </select> </form>
µÇ¼ºó¸´ÖÆ
ÔÚ·ÓÉÖÐÌí¼ÓÒÔÏ´úÂ룬ÒԱ㴦ÀíÀ´×ÔÓïÑÔÑ¡Ïî±íµ¥µÄÇëÇó£º
Route::post('locale', function(Request $request) { App::setLocale($request->locale); return redirect()->back(); });
µÇ¼ºó¸´ÖÆ
Õâ»á¸üÐÂÄ¿½ñ»á»°ÖеÄÓïÑÔÑ¡Ï²¢Öض¨Ïòµ½ÉÏÒ»Ò³¡£
½áÂÛ
ʹÓÃLaravel LocalizationÖ¼ÔÚ¼ò»¯¶àÓïÑÔÖ§³Ö£¬ÒÔ±ãÔÚLaravelÓ¦ÓóÌÐòÖÐÇáËɵØÍâµØ»¯ËùÓÐÒ³ÃæÔªËØ¡£±¾ÎÄÖÐÏÈÈݵİ취¿ÉÓÃ×÷ÔÚLaravelÓ¦ÓóÌÐòÖÐʵÏÖ¶àÓïÑÔÖ§³ÖµÄÆðµã¡£ÏÖʵÀú³ÌÖУ¬»¹¿ÉÒÔƾ֤ӦÓóÌÐòµÄÐèÒª¾ÙÐÐÊʵ±µÄµ÷½âºÍ¶¨ÖÆ¡£
ÒÔÉϾÍÊÇLaravel¿ª·¢£ºÔõÑùʹÓÃLaravel LocalizationʵÏÖ¶àÓïÑÔÖ§³Ö£¿µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡