dothanhtai/laravel-localization

为 Laravel 提供简单的本地化

dev-master 2020-05-07 09:32 UTC

This package is auto-updated.

Last update: 2024-09-07 19:54:01 UTC


README

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

目录

Laravel 兼容性

Laravel 5 已发布!!

安装

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

config/app.php 中注册 ServiceProvider

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

您还可以注册 LaravelLocalization Facade

        'aliases' => [
		// [...]
                'LaravelLocalization' => Dothanhtai\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' => \Dothanhtai\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
		'localizationRedirect' => \Dothanhtai\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
		'localeSessionRedirect' => \Dothanhtai\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
                'localeViewPath' => \Dothanhtai\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()中存在于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' => 'Dothanhtai\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="Dothanhtai\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 数组)。