nguyen930411/laravel-localization

为Laravel提供易于使用的本地化

dev-master 2022-03-28 02:50 UTC

This package is auto-updated.

Last update: 2024-09-28 08:14:45 UTC


README

为Laravel提供易于使用的i18n本地化,是一个与Laravel本地化类结合的有用工具。

目录

Laravel兼容性

Laravel 5已发布!!

安装

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

config/app.php中注册ServiceProvider

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

您还可以注册LaravelLocalization Facade

        'aliases' => [
		// [...]
                'LaravelLocalization' => Nguyen930411\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' => \Nguyen930411\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
		'localizationRedirect' => \Nguyen930411\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
		'localeSessionRedirect' => \Nguyen930411\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
                'localeViewPath' => \Nguyen930411\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() }}

此函数将返回所有支持的语言及其属性数组。

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

/**
 * 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>

在此示例中,默认语言将强制在getLocalizedURL()中出现,即使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' => 'Nguyen930411\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函数。

然后您必须创建翻译文件并将您想要翻译的每个键添加到其中。我建议在您的资源文件夹中的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="Nguyen930411\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 中的 providers 数组)。