relictos/laravel-localization

为Laravel提供简易的本地化

dev-master 2017-02-10 15:36 UTC

This package is not auto-updated.

Last update: 2024-09-14 20:45:51 UTC


README

Join the chat at https://gitter.im/mcamara/laravel-localization

Latest Stable Version Total Downloads Build Status

为Laravel提供简易的国际化本地化,是一个与Laravel本地化类相结合的有用工具。

目录

Laravel兼容性

Laravel 5已发布!!

安装

Composer

将Laravel本地化添加到您的composer.json文件中。

"mcamara/laravel-localization": "1.1.*"

运行composer install以获取该包的最新版本。

手动

建议使用Composer,但您也可以从该存储库下载和安装。

Laravel

Laravel本地化包含一个服务提供者,用于Laravel。您需要按照上述步骤将其添加到composer.json中,然后注册服务提供者到您的应用程序中。

打开config/app.php并找到providers键。将LaravelLocalizationServiceProvider添加到数组中。

	...
	Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider::class
	...

您还可以在相同文件中添加类别名列表的别名。

	...
	'LaravelLocalization'	=> Mcamara\LaravelLocalization\Facades\LaravelLocalization::class
	...

使用方法

Laravel本地化使用请求的URL。为了实现这个目的,应在routes.php文件中添加一个路由组。它将筛选所有需要本地化的页面。

	// app/Http/routes.php

	Route::group(['prefix' => LaravelLocalization::setLocale()], function()
	{
		/** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
		Route::get('/', function()
		{
			return View::make('hello');
		});

		Route::get('test',function(){
			return View::make('test');
		});
	});

	/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/

一旦这个路由组添加到路由文件中,用户就可以访问在supportedLocales中添加的所有语言环境(默认为'en'和'es',查看配置部分以更改此选项)。例如,用户现在可以使用以下地址访问两个不同的语言环境

	http://url-to-laravel/en
	http://url-to-laravel/es
	http://url-to-laravel

如果URL中没有语言环境或者它未在supportedLocales中定义,系统将使用应用程序的默认语言环境或用户的浏览器默认语言环境(如果配置文件中已定义)。

一旦定义了语言环境,该语言环境变量将被存储在会话中(如果启用了中间件),因此一旦定义,就不需要在URL中写入/lang/部分,使用用户的最后一个已知语言环境。如果用户访问不同的语言环境,此会话值将更改,将翻译他访问的任何其他页面为最后选择的语言环境。

模板文件和所有语言环境文件应遵循Lang类

中间件

此外,此包包含一个中间件对象,可以将所有"非本地化"路由重定向到相应的"本地化"路由。

因此,如果用户导航到http://url-to-laravel/test,并且系统启用了此中间件,当前用户的语言环境为'en',系统会自动将其重定向(301)到http://url-to-laravel/en/test。这主要是为了避免重复内容并提高SEO性能。

为此,您需要在app/Http/Kernel.php文件中注册此中间件,如下所示

	<?php namespace App\Http;

	use Illuminate\Foundation\Http\Kernel as HttpKernel;

	class Kernel extends HttpKernel {
		/**
		 * The application's route middleware.
		 *
		 * @var array
		 */
		protected $routeMiddleware = [
			/**** OTHER MIDDLEWARE ****/
			'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
			'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
			'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class
			// REDIRECTION MIDDLEWARE
		];

	}
	// app/Http/routes.php

	Route::group(
	[
		'prefix' => LaravelLocalization::setLocale(),
		'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]
	],
	function()
	{
		/** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
		Route::get('/', function()
		{
			return View::make('hello');
		});

		Route::get('test',function(){
			return View::make('test');
		});
	});

	/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/

为了激活它,您只需将此中间件附加到您希望可访问本地化的路由上。

如果您想隐藏默认语言环境但总是显示其他语言环境在URL中,将hideDefaultLocaleInURL配置值切换为true。一旦为true,如果默认语言环境为'en'(英语),则包含/en/的所有URL都会重定向到没有此片段的同一URL,但保持语言环境为'en'(英语)。

重要 - 当 hideDefaultLocaleInURL 设置为 true 时,未本地化的根将被视为应用的默认地区 app.locale。因此,当 hideDefaultLocaleInURL 为 true 时,将 永不 发生使用 Accept-Language 标头的语言协商。

辅助函数

此软件包包含一些有用的功能,例如

获取特定地区的 URL

	/**
	 * Returns an URL adapted to $locale
	 *
	 * @param  string|boolean 	$locale	   	Locale to adapt, false to remove locale
	 * @param  string|false		$url		URL to adapt in the current language. If not passed, the current url would be taken.
	 * @param  array 			$attributes	Attributes to add to the route, if empty, the system would try to extract them from the url.
	 *
	 * @throws UnsupportedLocaleException
	 *
	 * @return string|false				URL translated, False if url does not exist
	 */
	public function getLocalizedURL($locale = null, $url = null, $attributes = array())

	//Should be called in a view like this:
	{{ LaravelLocalization::getLocalizedURL(optional string $locale, optional string $url, optional array $attributes) }}

它返回一个本地化到所需地区的 URL。

获取干净的路线

	/**
	 * It returns an URL without locale (if it has it)
	 * Convenience function wrapping getLocalizedURL(false)
	 *
	 * @param  string|false 	$url	  URL to clean, if false, current url would be taken
	 *
	 * @return string		   URL with no locale in path
	 */
	public function getNonLocalizedURL($url = null)

	//Should be called in a view like this:
	{{ LaravelLocalization::getNonLocalizedURL(optional string $url) }}

它返回一个去除所有本地化的 URL。

获取特定翻译键的 URL

	/**
	 * Returns an URL adapted to the route name and the locale given
	 *
     * @throws UnsupportedLocaleException
     *
	 * @param  string|boolean 	$locale 			Locale to adapt
	 * @param  string 			$transKeyName  		Translation key name of the url to adapt
	 * @param  array 			$attributes  		Attributes for the route (only needed if transKeyName needs them)
	 *
	 * @return string|false 	URL translated
	 */
	public function getURLFromRouteNameTranslated($locale, $transKeyName, $attributes = array())

	//Should be called in a view like this:
	{{ LaravelLocalization::getURLFromRouteNameTranslated(string $locale, optional array $transKeyNames, optional array $attributes) }}

它返回一个路线,使用传递的本地化进行本地化。如果翻译键在给定的地区中不存在,此函数将返回 false。

获取支持的地区

	/**
     * Return an array of all supported Locales
     *
     * @return array
     */
     public function getSupportedLocales()

	//Should be called like this:
	{{ LaravelLocalization::getSupportedLocales() }}

此函数将返回所有支持的地区及其属性作为数组。

获取支持的地区键

	/**
	 * Returns supported languages language key
	 *
	 * @return array 	keys of supported languages
	 */
	public function getSupportedLanguagesKeys()

	//Should be called like this:
	{{ LaravelLocalization::getSupportedLanguagesKeys() }}

此函数将返回包含所有支持地区键的数组。

设置地区

	/**
     * Set and return current locale
     *
     * @param  string $locale	        Locale to set the App to (optional)
     *
     * @return string 			        Returns locale (if route has any) or null (if route does not have a locale)
     */
    public function setLocale($locale = null)

	//Should be called in a view like this:
	{{ LaravelLocalization::setLocale(optional string $locale) }}

此函数将更改应用的当前地区。如果没有传递地区,地区将通过cookie(如果之前存储过)、会话(如果之前存储过)、浏览器 Accept-Language 标头或默认应用地区(取决于您的配置文件)确定。

必须在任何应翻译的路由的前缀中调用此函数(有关更多信息,请参阅过滤器部分)。

获取当前地区

    /**
     * Returns current language
     *
     * @return string current language
     */
    public function getCurrentLocale()

	//Should be called in a view like this:
	{{ LaravelLocalization::getCurrentLocale() }}

此函数将返回当前地区的键。

获取当前地区名称

	/**
	 * Returns current locale name
	 *
	 * @return string current locale name
	 */
	public function getCurrentLocaleName()

	//Should be called in a view like this:
	{{ LaravelLocalization::getCurrentLocaleName() }}

此函数将返回当前地区名称的字符串(英语/西班牙语/阿拉伯语/等等)。

获取当前地区方向

	/**
	 * Returns current locale direction
	 *
	 * @return string current locale direction
	 */
	public function getCurrentLocaleDirection()

	//Should be called in a view like this:
	{{ LaravelLocalization::getCurrentLocaleDirection() }}

此函数将返回当前地区方向的字符串(ltr/rtl)。

获取当前地区脚本

	/**
	 * Returns current locale script
	 *
	 * @return string current locale script
	 */
	public function getCurrentLocaleScript()

	//Should be called in a view like this:
	{{ LaravelLocalization::getCurrentLocaleScript() }}

此函数将返回当前地区脚本作为字符串的 ISO 15924 代码;“Latn”,“Cyrl”,“Arab”等。

创建语言选择器

如果您在项目中支持多个地区,您可能希望提供一种方式让用户更改语言。以下是一个简单的 blade 模板代码示例,您可以使用它来创建自己的语言选择器。

<ul class="language_bar_chooser">
	@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
        <li>
            <a rel="alternate" hreflang="{{$localeCode}}" href="{{LaravelLocalization::getLocalizedURL($localeCode) }}">
                {{{ $properties['native'] }}}
            </a>
        </li>
	@endforeach
</ul>

已翻译路由

您可以根据要显示的语言调整您的 URL。例如,http://url/en/abouthttp://url/es/acerca(acerca 是西班牙语中的“关于”)或 http://url/en/view/5http://url/es/ver/5(view 在西班牙语中等于 ver),将重定向到使用适当的过滤器设置翻译文件的同一路由控制器。

因为它是一个中间件,首先您必须在 app/Http/Kernel.php 文件中注册它,如下所示

	<?php namespace App\Http;

	use Illuminate\Foundation\Http\Kernel as HttpKernel;

	class Kernel extends HttpKernel {
		/**
		 * The application's route middleware.
		 *
		 * @var array
		 */
		protected $routeMiddleware = [
			/**** OTHER MIDDLEWARE ****/
			'localize' => 'Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes',
			// TRANSLATE ROUTES MIDDLEWARE
		];

	}
	// app/Http/routes.php

	Route::group(
	[
		'prefix' => LaravelLocalization::setLocale(),
		'middleware' => [ 'localize' ] // Route translate middleware
	],
	function()
	{
      /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
      Route::get('/', function()
      {
      	// This routes is useless to translate
      	return View::make('hello');
      });

      Route::get(LaravelLocalization::transRoute('routes.about'),function(){
          return View::make('about');
      });
      Route::get(LaravelLocalization::transRoute('routes.view'),function($id){
          return View::make('view',['id'=>$id]);
      });
	});

	/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/

在路由文件中,您只需为想要翻译的每个路由添加 LaravelLocalizationRoutes 过滤器和 LaravelLocalization::transRoute 函数。

然后,您必须创建翻译文件,并添加您想要翻译的所有键。我建议在您的 resources/lang/language_abbreviation 文件夹内创建一个 routes.php 文件。对于前面的示例,我创建了两个翻译文件,这两个文件看起来如下

	// resources/lang/en/routes.php
    return [
      "about" 		=> 	"about",
      "view" 		=> 	"view/{id}", //we add a route parameter
      // other translated routes
	];
	// resources/lang/es/routes.php
    return [
      "about" 		=> 	"acerca",
      "view" 		=> 	"ver/{id}", //we add a route parameter
      // other translated routes
	];

文件保存后,您可以无障碍访问http://url/en/abouthttp://url/es/acercahttp://url/en/view/5http://url/es/ver/5getLanguageBar函数将按预期工作,并将路由转换为所有已翻译的语言(别忘了将任何新路由添加到翻译文件中)。

事件

如果您想翻译URL参数,可以在翻译时捕获它们。要这样做,只需为routes.translation事件创建一个事件监听器,如下所示:

Event::listen('routes.translation', function($locale, $attributes)
{
	// Do your magic

    return $attributes;
});

请确保将区域设置和属性作为参数传递给闭包。您还可以使用事件订阅者,参见:https://laravel.net.cn/docs/events#event-subscribers

配置

配置文件

要编辑此包的默认配置,可以执行以下操作:

php artisan vendor:publish --provider="Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider"

之后,将创建config/laravellocalization.php文件。在这个文件中,您将找到可以在此包中编辑的所有字段。

服务提供者

否则,您可以使用ConfigServiceProviders(更多信息请参阅此文件)。

例如,编辑Laravel安装时Laravel加载的默认配置服务提供者。此文件位于app/providers/ConfigServicePovider.php,如下所示:

	<?php namespace App\Providers;

	use Illuminate\Support\ServiceProvider;

	class ConfigServiceProvider extends ServiceProvider {
		public function register()
		{
			config([
				'laravellocalization.supportedLocales' => [
					'ace' => array( 'name' => 'Achinese', 'script' => 'Latn', 'native' => 'Aceh' ),
					'ca'  => array( 'name' => 'Catalan', 'script' => 'Latn', 'native' => 'català' ),
					'en'  => array( 'name' => 'English', 'script' => 'Latn', 'native' => 'English' ),
				],

				'laravellocalization.useAcceptLanguageHeader' => true,

				'laravellocalization.hideDefaultLocaleInURL' => true
			]);
		}

	}

此配置将添加加泰罗尼亚语和阿昌语作为语言,并覆盖任何其他先前支持的区域设置以及包中的所有其他选项。

您可以创建自己的配置提供者,并将它们添加到应用程序配置文件中(请参阅config/app.php中的提供者数组)。

变更日志

在此处查看变更日志 -> changelog

许可协议

Laravel Localization是一个开源的Laravel包,许可协议为MIT。