Laravel 是一个为本地化设计的应用程序,以适应各种语言和文化。 本地化通过翻译为特定语言定制国际化应用程序。
localhost
. 如果不是,请更换 localhost
使用您自己的域名或 IP 地址(取决于您的安装)。在 Laravel 中,就像在许多其他框架中一样,我们可以将不同语言的翻译存储在单独的文件中。 组织 Laravel 翻译文件的方式有两种:
resources/lang/{en,fr,ru}/{myfile.php}
;resources/lang/{fr.json, ru.json}
;对于地域不同的语言,你应该给它们命名 directory/file
符合 ISO 15897 的语言。例如,对于英国英语,您将使用 en_GB
而不是 en-gb
. 在本文中,我们将重点关注第二种方法,但第一种方法也是如此(除了如何命名和检索翻译键)。
现在,让我们去 resources/views/welcome.blade.php
文件并替换的内容 body
用我们的标记,像这样:
<body class="antialiased">
<div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
<div class="max-w-6xl mx-auto sm:px-6 lg:px-8">
<div class="flex justify-center pt-8 sm:justify-start sm:pt-0">
Welcome to our website
</div>
</div>
</div>
</body>
我们将从准备本地化欢迎消息开始,这在 Laravel 中非常容易。 您所要做的就是用以下代码替换文本“欢迎访问我们的网站”: {{ __('Welcome to our website') }}
。 这将指示 Laravel 默认显示“欢迎来到我们的网站”defi如果设置了英语以外的语言(我们稍后会介绍),则查找该字符串的翻译。 英语将被设置为默认语言defi我们的应用程序完成了,所以默认设置defi最后我们将简单地显示文本“欢迎来到我们的网站”。 如果语言环境不同,我们将尝试找到匹配的翻译,稍后就会创建它。
但是 Laravel 是如何知道当前是哪种语言或者应用中有哪些语言可用呢? 它通过查看应用程序中的本地配置来执行此操作 config/app.php
. 打开此文件并查找这两个关联数组键:
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
键上方显示的描述应该是不言自明的,但简而言之,键 locale
包含本地预defi完成您的应用程序(至少,如果代码中没有设置其他区域设置)。 还有 fallback_locale
如果我们在我们的应用程序中设置了一个不存在的语言环境,它就会被激活。
当我们打开这个文件时,让我们添加一个新键以方便列出我们的应用程序将支持的所有语言环境。 稍后我们将在添加本地切换器时使用它。 然而,这是一项可选任务,因为 Laravel 不要求我们这样做。
/*
|--------------------------------------------------------------------------
| Available locales
|--------------------------------------------------------------------------
|
| List all locales that your application works with
|
*/
'available_locales' => [
'English' => 'en',
'Italian' => 'it',
'French' => 'fr',
],
现在我们的应用程序支持三种语言:英语、意大利语和法语。
现在我们已经建立了我们将使用的所有区域设置,我们可以继续翻译我们的欢迎消息defi晚上。
让我们从向文件夹中添加新的本地化文件开始 resources/lang
. 首先,创建一个文件 resources/lang/it.json
并添加相应的翻译,如下:
{
"Welcome to our website": "Benvenuto nel nostro sito web"
}
接下来,创建一个文件 resources/lang/fr.json
:
{
“欢迎来到我们的网站”: “欢迎来到我们的网站”
}
正如你所看到的,我们总是参考前言defi我们在文件中添加的 nito welcome.blade.php
(这是 {{ __('Welcome to our website') }}
). 我们不必创建文件的原因 en.json
这是因为Laravel已经通过预先设置知道我们传递哪些消息defi完成功能 __()
他们是为了我们当地的预defi尼托恩
此时,Laravel 不知道如何更改语言环境,因此现在,让我们直接在路径内进行翻译。 修改欢迎路径预defi完成后如下图:
Route::get('/{locale?}', function ($locale = null) {
if (isset($locale) && in_array($locale, config('app.available_locales'))) {
app()->setLocale($locale);
}
return view('welcome');
});
我们现在可以访问我们的网站,指定任何可用的语言作为第一个路径段:例如, localhost/ru
o localhost/fr
. 您应该看到本地化的内容。 如果你指定了一个不受支持的语言环境或者根本没有指定语言环境,Laravel 将使用 en
默认情况下defi妮塔。
为每个站点链接切换语言环境可能不是您想要的,而且看起来可能不那么美观。 这就是为什么我们将通过特殊的语言切换器进行语言设置,并使用用户会话来显示翻译后的内容。 因此,在里面创建一个新的中间件 app/Http/Middleware/Localization.php
文件或通过运行 artisan make:middleware Localization
.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
class Localization
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (Session::has('locale')) {
App::setLocale(Session::get('locale'));
}
return $next($request);
}
}
如果会话中存在此选择,此中间件将指示 Laravel 使用用户选择的语言环境。
由于我们需要在每个请求上完成此操作,因此我们还需要将其添加到预中间件堆栈中defi完成于 app/http/Kernel.php
为 web
中间件组:
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Localization::class, /* <--- add this */
],
接下来,我们需要添加一个路径来更改语言环境。 我们正在使用闭包路径,但如果您愿意,您可以在控制器中使用完全相同的代码:
Route::get('language/{locale}', function ($locale) {
app()->setLocale($locale);
session()->put('locale', $locale);
return redirect()->back();
});
另外,不要忘记删除之前在我们的预欢迎路径中添加的区域设置切换defi晚上:
Route::get('/', function () {
return view('welcome');
});
完成后,用户更改当前设置语言的唯一方法是输入 localhost/language/{locale}
。 的 locale
选择将存储在会话中并将用户重定向到他们来自的地方(检查 Localization
中间件)。 要尝试,请访问 localhost/language/ru
(只要您的浏览器中存在会话 cookie),您就会看到翻译后的内容。 您可以在网站上自由移动或尝试刷新页面并查看所选语言是否已保留。
现在我们需要创建一些东西,用户可以单击它来更改语言,而不是手动将本地代码输入到 URL 中。 为此,我们将添加一个非常简单的语言检查器。 因此,创建一个新的 resources/views/partials/language_switcher.blade.php
包含以下代码的文件:
<div class="flex justify-center pt-8 sm:justify-start sm:pt-0">
@foreach($available_locales as $locale_name => $available_locale)
@if($available_locale === $current_locale)
<span class="ml-2 mr-2 text-gray-700">{{ $locale_name }}</span>
@else
<a class="ml-1 underline ml-2 mr-2" href="language/{{ $available_locale }}">
<span>{{ $locale_name }}</span>
</a>
@endif
@endforeach
</div>
在“欢迎”视图中包含新创建的切换器:
<body class="antialiased">
<div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
<div class="max-w-6xl mx-auto sm:px-6 lg:px-8">
@include('partials/language_switcher')
<div class="flex justify-center pt-8 sm:justify-start sm:pt-0">
{{ __('Welcome to our website') }}
</div>
</div>
</div>
</body>
打开 app/Providers/AppServiceProvider.php
文件并添加代码以在我们的语言切换器组成时共享。 具体来说,我们将共享可以作为文件访问的当前语言环境 {{ $current_locale }}
.
我们将主要与 resources/views/welcome.blade.php
,因此除非另有说明,否则一切都必须在我们欢迎的视图中发生。
例如,让我们向假想的用户 (Amanda) 打招呼,而不是只显示一条通用消息:
{{ __('Welcome to our website, :Name', ['name' => 'caroline']) }}
请注意,我们使用首字母小写的名称,但首字母大写的占位符。 这样,Laravel 可以帮助您自动将实际单词大写。 如果占位符以大写字母开头,则会发生这种情况,例如, :Name
产生“Caroline”或一个完全大写的单词, :NAME
, 产生“CAROLINE”。
我们还更新了翻译文件 resources/lang/fr.json
e resources/lang/it.json
,因为目前我们只能在任何地方看到英文版本,因为翻译键与翻译不匹配。
法语:
{
"Welcome to our website, :Name": "Bienvenue sur notre site, :Name"
}
意大利:
{
"Welcome to our website, :Name": "Benvenuto sul nostro sito web, :Name"
}
要查看复数化的实际效果,让我们添加一段新的文本。
要执行复数化,您必须使用函数 trans_choice
而不是 __()
, 例如:
{{ __('Welcome to our website, :Name', ['name' => 'caroline']) }}
<br>
{{ trans_choice('There is one apple|There are many apples', 2) }}
如您所见,复数形式由 a 分隔 |
.
现在,如果我们需要多个复数形式怎么办?
这也是可能的:
{{ trans_choice('{0} There :form no apples|{1} There :form just :count apple|[2,19] There :form :count apples', 24) }}
在这种情况下,我们允许数字 0
, 1
,而 2
a 19
,终于从20开始了。 当然,您可以根据需要添加任意数量的规则。
那么如果我们想要复数形式的占位符呢?
{{ trans_choice('{0} There :form no apples|{1} There :form just :count apple|[2,19] There :form :count apples', 24, ['form' => 'is']) }}
如果需要,我们还可以使用占位符使用传入 `trans_choice` 的计数 :count
特别的:
{{ trans_choice('{0} There :form no apples|{1} There :form just :count apple|[2,19] There :form :count apples', 1, ['form' => 'is']) }}
最后,不要忘记使用您对基础翻译所做的任何更改来更新您的翻译文件。
意大利:
{
"Welcome to our website, :Name": "Benvenuto nel nostro sito, :Name",
"{0} There :form no apples|{1} There :form just :count apple|[2,19] There :form :count apples": "{0} Nessuna mela|{1} C'è:count mela|[2,19] Ci sono :count mele"
}
法语:
{
"Welcome to our website, :Name": "Bienvenue sur notre site, :Name",
"{0} There :form no apples|{1} There :form just :count apple|[2,19] There :form :count apples": "{0} Il n'y a pas de pommes|{1} Il n'y :form :count pomme|[2,19] Il y :form :count pommes"
}
为了定位日期,我们将利用 碳 ,Laravel 默认自带的defi妮塔。 查看 碳文档 ; 你可以做很多有趣的事情。 例如,我们可以使用日期和时间规则来设置我们的语言环境。
对于我们的简单示例,我们将显示针对所选语言本地化的当前日期。 在我们的 routes/web.php
,我们更新欢迎页面路径并将本地化日期消息传递给我们 view
欢迎:
<?php
Route::get('/', function () {
$today = \Carbon\Carbon::now()
->settings(
[
'locale' => app()->getLocale(),
]
);
// LL is macro placeholder for MMMM D, YYYY (you could write same as dddd, MMMM D, YYYY)
$dateMessage = $today->isoFormat('dddd, LL');
return view('welcome', [
'date_message' => $dateMessage
]);
});
让我们更新 resources/views/welcome.blade.php
添加日期显示,像这样:
{{ __('Welcome to our website, :Name', ['name' => 'amanda']) }}
<br>
{{ trans_choice('{0} There :form :count apples|{1} There :form just :count apple|[2,19] There :form :count apples', 1, ['form' => 'is']) }}
<br>
{{ $date_message }}
尝试更改主页上的语言 localhost
,我们将看到日期现在已本地化,例如:
在不同的国家,人们使用不同的格式来表示数字,例如:
因此,要在你的 Laravel 应用程序中反映这些差异,你可以使用 数字格式器 通过以下方式:
<?php
$num = NumberFormatter::create('en_US', NumberFormatter::DECIMAL);
$num2 = NumberFormatter::create('fr', NumberFormatter::DECIMAL);
您还可以用特定语言编写数字并显示类似“十二万三千一百二十三点一二”的内容:
<?php
$num = NumberFormatter::create('en_US', NumberFormatter::SPELLOUT);
$num2 = NumberFormatter::create('fr', NumberFormatter::SPELLOUT);
此外,NumberFormatter 允许您轻松定位货币,例如:
<?php
$currency1 = NumberFormatter::create('fr', NumberFormatter::CURRENCY);
$currency2 = NumberFormatter::create('en_US', NumberFormatter::CURRENCY);
因此对于 fr
你会看到欧元,而对于 en_US
货币将以美元为单位。
Ercole Palmeri