georgechaduneli/laravel-localization

Laravel的本地化解决方案

dev-master 2020-06-18 20:35 UTC

This package is auto-updated.

Last update: 2024-08-29 04:08:53 UTC


README

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

Latest Stable Version Total Downloads Build Status

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

目录

Laravel兼容性

安装

通过Composer安装包: composer require mcamara/laravel-localization

在Laravel 5.5中,服务提供者和外观将自动注册。对于框架的旧版本,请按照以下步骤操作

config/app.php 中注册服务提供者

        'providers' => [
		// [...]
                Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider::class,
        ],

您还可以注册 LaravelLocalization 外观

        'aliases' => [
		// [...]
                '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,
                'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class
		// REDIRECTION MIDDLEWARE
	];
}
// app/Http/routes.php

Route::group(
[
	'prefix' => LaravelLocalization::setLocale(),
	'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
],
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 头部的语言协商。

将当前语言环境设置为视图基本路径

要将当前语言环境设置为视图基本路径,只需在 Kernel.php 中注册 localeViewPath-middleware,就像上面描述的那样。

现在您可以将视图包裹在基于语言的文件夹中,就像翻译文件一样。

resources/views/en/resources/vies/fr,...

辅助函数

此软件包包含一些有用的函数,例如

获取特定语言环境的 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 stringURL 			  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() }}

// To exclude current locale from returned array
{{ LaravelLocalization::getSupportedLocales(true) }}

此函数将返回所有支持的语言环境和它们的属性作为数组。

获取支持的语言环境自定义顺序

/**
 * Return an array of all supported Locales but in the order the user
 * has specified in the config file. Useful for the language selector.
 *
 * @return array
 */
public function getLocalesOrder()

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

此函数将返回所有支持的语言环境,但顺序与配置文件中指定的顺序相同。您可以使用此函数在语言选择器中打印语言环境。

获取支持的语言环境键

/**
 * 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>
    @foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
        <li>
            <a rel="alternate" hreflang="{{ $localeCode }}" href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
                {{ $properties['native'] }}
            </a>
        </li>
    @endforeach
</ul>

如果您想在语言选择器中排除当前语言环境,请这样做。

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

在此,默认语言将强制在 getLocalizedURL() 中存在于 URL 中,即使 hideDefaultLocaleInURL = true

已翻译路由

您可以根据要显示的语言调整您的 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/5

事件

如果您希望将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安装时加载的默认配置服务提供者。此文件位于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中的提供者数组)。

缓存路由

如果您希望对所有语言的路由进行缓存,请参阅此包:https://github.com/czim/laravel-localization-route-cache

变更日志

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

许可证

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