Readouble

Laravel 9.x 多言語化

イントロダクションIntroduction

Laravelの多言語機能は、さまざまな言語の文字列を取得する便利な方法を提供し、アプリケーション内で複数の言語を簡単にサポートできるようにしています。Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application.

Laravelでは、翻訳文字列を管理する方法が2つあります。まず、言語文字列をlangディレクトリ内のファイルへ格納する方法です。このディレクトリの中には、アプリケーションでサポートする各言語のサブディレクトリを用意します。これは、バリデーションエラーメッセージのような、Laravelの組み込み機能の翻訳文字列を管理するためにも使用されている方法です。Laravel provides two ways to manage translation strings. First, language strings may be stored in files within the lang directory. Within this directory, there may be subdirectories for each language supported by the application. This is the approach Laravel uses to manage translation strings for built-in Laravel features such as validation error messages:

/lang
    /en
        messages.php
    /es
        messages.php

もしくは、翻訳文字列をlangディレクトリ下のJSON ファイルで定義することもできます。この方法を取る場合、アプリケーションがサポートする各言語ごとに、このディレクトリの中に対応するJSONファイルを用意します。この方法は、翻訳可能な文字列が大量にあるアプリケーションに推奨します。Or, translation strings may be defined within JSON files that are placed within the lang directory. When taking this approach, each language supported by your application would have a corresponding JSON file within this directory. This approach is recommended for applications that have a large number of translatable strings:

/lang
    en.json
    es.json

このドキュメントでは、翻訳文字列を管理する各アプローチについて説明します。We'll discuss each approach to managing translation strings within this documentation.

ロケールの設定Configuring The Locale

アプリケーションのデフォルト言語は、config/app.php設定ファイルのlocale設定オプションに保存します。アプリケーションのニーズに合わせて、この値を自由に変更してください。The default language for your application is stored in the config/app.php configuration file's locale configuration option. You are free to modify this value to suit the needs of your application.

Appファサードが提供するsetLocaleメソッドを使用して、単一のHTTPリクエストの間のデフォルト言語を実行時に変更できます。You may modify the default language for a single HTTP request at runtime using the setLocale method provided by the App facade:

use Illuminate\Support\Facades\App;

Route::get('/greeting/{locale}', function ($locale) {
    if (! in_array($locale, ['en', 'es', 'fr'])) {
        abort(400);
    }

    App::setLocale($locale);

    //
});

「フォールバック言語」も設定できます。これは、アクティブな言語に対応する特定の翻訳文字列が含まれていない場合に使用されます。デフォルト言語と同様に、フォールバック言語もconfig/app.php設定ファイルで指定します。You may configure a "fallback language", which will be used when the active language does not contain a given translation string. Like the default language, the fallback language is also configured in the config/app.php configuration file:

'fallback_locale' => 'en',

現在のロケールの決定Determining The Current Locale

AppファサードのcurrentLocaleメソッドとisLocaleメソッドを使用して、現在のロケールを判定したり、ロケールが指定する値であるかどうかを確認したりできます。You may use the currentLocale and isLocale methods on the App facade to determine the current locale or check if the locale is a given value:

use Illuminate\Support\Facades\App;

$locale = App::currentLocale();

if (App::isLocale('en')) {
    //
}

言語の複数形Pluralization Language

Laravelの「複数形化機能(Pluralizer)」は、Eloquentやフレームワークの他の部分で単数形の文字列を複数形の文字列に変換するために使用していますが、英語以外の言語を使用するように指示できます。これは、アプリケーションのサービスプロバイダのbootメソッドの中でuseLanguageメソッドを呼び出して、実現します。現在サポートしている言語は、フランス語(french)、ノルウェー語ーブークモール(norwegian-bokmal)、ポルトガル語(portuguese)、スペイン語(spanish)、トルコ語(turkish)です。You may instruct Laravel's "pluralizer", which is used by Eloquent and other portions of the framework to convert singular strings to plural strings, to use a language other than English. This may be accomplished by invoking the useLanguage method within the boot method of one of your application's service providers. The pluralizer's currently supported languages are: french, norwegian-bokmal, portuguese, spanish, and turkish:

use Illuminate\Support\Pluralizer;

/**
 * アプリケーションの全サービスの初期起動処理
 *
 * @return void
 */
public function boot()
{
    Pluralizer::useLanguage('spanish');

    // ...
}

warning Warning! 言語の複数形化をカスタマイズする場合、Eloquentモデルのテーブル名は、明示的に定義する必要があります。Warning
If you customize the pluralizer's language, you should explicitly define your Eloquent model's table names[/docs/{{version}}/eloquent#table-names].

翻訳文字列の定義Defining Translation Strings

短縮キーの使用Using Short Keys

通常、翻訳文字列はlangディレクトリにあるファイルに格納します。このディレクトリの中に、アプリケーションがサポートする各言語のサブディレクトリがあるはずです。これは、バリデーションエラーメッセージのような、Laravelの組み込み機能の翻訳文字列を管理するために、Laravelが採用している方法です。Typically, translation strings are stored in files within the lang directory. Within this directory, there should be a subdirectory for each language supported by your application. This is the approach Laravel uses to manage translation strings for built-in Laravel features such as validation error messages:

/lang
    /en
        messages.php
    /es
        messages.php

すべての言語ファイルは、キー付き文字列の配列を返します。例えば:All language files return an array of keyed strings. For example:

<?php

// lang/en/messages.php

return [
    'welcome' => 'Welcome to our application!',
];

warning Warning! 地域によって異なる言語の場合、ISO15897に従って言語ディレクトリに名前を付ける必要があります。たとえば、「en-gb」ではなく「en_GB」をイギリス英語に使用する必要があります。Warning
For languages that differ by territory, you should name the language directories according to the ISO 15897. For example, "en_GB" should be used for British English rather than "en-gb".

翻訳文字列をキーとして使用Using Translation Strings As Keys

翻訳可能な文字列が多数あるアプリケーションの場合、「短縮キー」ですべての文字列を定義すると、ビューでキーを参照するときに混乱する可能性があり、アプリケーションがサポートするすべての翻訳文字列のキーを継続的に作成するのは面倒です。For applications with a large number of translatable strings, defining every string with a "short key" can become confusing when referencing the keys in your views and it is cumbersome to continually invent keys for every translation string supported by your application.

このため、Laravelは、文字列の「デフォルト」翻訳をキーとして、翻訳文字列を定義するサポートも提供しています。翻訳文字列をキーとして使用する翻訳ファイルは、JSONファイルとして lang ディレクトリに格納します。例えば、アプリケーションにスペイン語の翻訳がある場合、lang/es.jsonファイルを作成する必要があります。For this reason, Laravel also provides support for defining translation strings using the "default" translation of the string as the key. Translation files that use translation strings as keys are stored as JSON files in the lang directory. For example, if your application has a Spanish translation, you should create a lang/es.json file:

{
    "I love programming.": "Me encanta programar."
}

キー/ファイルの競合Key / File Conflicts

他の翻訳ファイル名と競合する翻訳文字列キーを定義しないでください。たとえば、nl/action.phpファイルは存在するがnl.jsonファイルは存在しないときに、"NL"ロケールの__('Action')を翻訳すると、トランスレータはnl/action.phpの内容を返します。You should not define translation string keys that conflict with other translation filenames. For example, translating __('Action') for the "NL" locale while a nl/action.php file exists but a nl.json file does not exist will result in the translator returning the contents of nl/action.php.

翻訳文字列の取得Retrieving Translation Strings

__ヘルパ関数を使い、言語ファイルから翻訳文字列を取得できます。「短いキー」を使い、翻訳文字列を定義している場合は、キーを含むファイルとキー自身を「ドット」構文で、__関数に渡す必要があります。例として、lang/en/messages.phpという言語ファイルからwelcomeという翻訳文字列を取得してみましょう。You may retrieve translation strings from your language files using the __ helper function. If you are using "short keys" to define your translation strings, you should pass the file that contains the key and the key itself to the __ function using "dot" syntax. For example, let's retrieve the welcome translation string from the lang/en/messages.php language file:

echo __('messages.welcome');

指定する翻訳文字列が存在しない場合、__関数は翻訳文字列キーを返します。したがって、上記の例を使用すると、翻訳文字列が存在しない場合、__関数はmessages.welcomeを返します。If the specified translation string does not exist, the __ function will return the translation string key. So, using the example above, the __ function would return messages.welcome if the translation string does not exist.

デフォルトの翻訳文字列を翻訳キーとして使用している場合は、文字列のデフォルトの翻訳を__関数に渡す必要があります。If you are using your default translation strings as your translation keys[#using-translation-strings-as-keys], you should pass the default translation of your string to the __ function;

echo __('I love programming.');

この場合も、翻訳文字列が存在しない場合、__関数は指定する翻訳文字列キーを返します。Again, if the translation string does not exist, the __ function will return the translation string key that it was given.

Bladeテンプレートエンジンを使用している場合は、{{}}エコー構文を使用して翻訳文字列を表示できます。If you are using the Blade templating engine[/docs/{{version}}/blade], you may use the {{ }} echo syntax to display the translation string:

{{ __('messages.welcome') }}

翻訳文字列中のパラメータの置換Replacing Parameters In Translation Strings

必要に応じて、翻訳文字列にプレースホルダーを定義できます。すべてのプレースホルダーには接頭辞:が付いています。たとえば、プレースホルダー名を使用してウェルカムメッセージを定義できます。If you wish, you may define placeholders in your translation strings. All placeholders are prefixed with a :. For example, you may define a welcome message with a placeholder name:

'welcome' => 'Welcome, :name',

翻訳文字列を取得するときにプレースホルダーを置き換えるには、置換の配列を2番目の引数として__関数に渡します。To replace the placeholders when retrieving a translation string, you may pass an array of replacements as the second argument to the __ function:

echo __('messages.welcome', ['name' => 'dayle']);

プレースホルダーにすべて大文字が含まれている場合、または最初の文字のみが大文字になっている場合、変換された値はそれに応じて大文字になります。If your placeholder contains all capital letters, or only has its first letter capitalized, the translated value will be capitalized accordingly:

'welcome' => 'Welcome, :NAME', // Welcome, DAYLE
'goodbye' => 'Goodbye, :Name', // Goodbye, Dayle

オブジェクト置換フォーマットObject Replacement Formatting

翻訳用のプレースホルダーとしてオブジェクトを指定する場合、 オブジェクトの__toStringメソッドを呼び出します。__toString](https://www.php.net/manual/ja/language.oop5.magic.php#object.tostring)メソッドは、PHP組み込みの「マジックメソッド」の一種です。しかし、サードパーティのライブラリに含まれるクラスとやり取りする場合など、指定するクラスの__toStringメソッドを制御できないこともあります。If you attempt to provide an object as a translation placeholder, the object's __toString method will be invoked. The __toString[https://www.php.net/manual/en/language.oop5.magic.php#object.tostring] method is one of PHP's built-in "magic methods". However, sometimes you may not have control over the __toString method of a given class, such as when the class that you are interacting with belongs to a third-party library.

このような場合のため、Laravelでは特定タイプのオブジェクトに対する、カスタムフォーマットハンドラを登録できます。これを行うには、トランスレータのstringableメソッドを呼び出す必要があります。stringableメソッドは、フォーマットに対応するオブジェクトタイプをタイプヒントする必要があります。通常、stringableメソッドはアプリケーションのAppServiceProviderクラスの、bootメソッド内で呼び出します。In these cases, Laravel allows you to register a custom formatting handler for that particular type of object. To accomplish this, you should invoke the translator's stringable method. The stringable method accepts a closure, which should type-hint the type of object that it is responsible for formatting. Typically, the stringable method should be invoked within the boot method of your application's AppServiceProvider class:

use Illuminate\Support\Facades\Lang;
use Money\Money;

/**
 * 全アプリケーションサービスの初期起動処理
 *
 * @return void
 */
public function boot()
{
    Lang::stringable(function (Money $money) {
        return $money->formatTo('en_GB');
    });
}

複数形Pluralization

別々の言語には複数形のさまざまな複雑なルールがあるため、複数形化は複雑な問題です。ただし、Laravelは、定義した複数形化ルールに基づいて文字列を異なる方法で翻訳する手助けができます。|文字を使用すると、文字列の単数形と複数形を区別できます。Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization; however, Laravel can help you translate strings differently based on pluralization rules that you define. Using a | character, you may distinguish singular and plural forms of a string:

'apples' => 'There is one apple|There are many apples',

もちろん、翻訳文字列をキーとして使用する場合でも、複数形化をサポートしています。Of course, pluralization is also supported when using translation strings as keys[#using-translation-strings-as-keys]:

{
    "There is one apple|There are many apples": "Hay una manzana|Hay muchas manzanas"
}

複数の値の範囲の変換文字列を指定する、より複雑な複数形化ルールを作成することもできます。You may even create more complex pluralization rules which specify translation strings for multiple ranges of values:

'apples' => '{0} There are none|[1,19] There are some|[20,*] There are many',

複数形化オプションのある翻訳文字列を定義した後、trans_choice関数を使用して、指定する「個数」に合った行を取得できます。以下の例では、個数が1より大きいため、複数形の翻訳文字列が返されます。After defining a translation string that has pluralization options, you may use the trans_choice function to retrieve the line for a given "count". In this example, since the count is greater than one, the plural form of the translation string is returned:

echo trans_choice('messages.apples', 10);

複数形化文字列でプレースホルダー属性を定義することもできます。これらのプレースホルダーは、trans_choice関数の3番目の引数として配列を渡すことで置き換えられます。You may also define placeholder attributes in pluralization strings. These placeholders may be replaced by passing an array as the third argument to the trans_choice function:

'minutes_ago' => '{1} :value minute ago|[2,*] :value minutes ago',

echo trans_choice('time.minutes_ago', 5, ['value' => 5]);

trans_choice関数に渡した整数値を表示したい場合は、組み込みの:countプレースホルダーを使用できます。If you would like to display the integer value that was passed to the trans_choice function, you may use the built-in :count placeholder:

'apples' => '{0} There are none|{1} There is one|[2,*] There are :count',

パッケージ言語ファイルのオーバーライドOverriding Package Language Files

パッケージは、独自の言語ファイルを用意している場合があります。調整するため、パッケージのコアファイルを変更する代わりに、lang/vendor/{package}/{locale}ディレクトリへファイルを配置し、上書きできます。Some packages may ship with their own language files. Instead of changing the package's core files to tweak these lines, you may override them by placing files in the lang/vendor/{package}/{locale} directory.

例えば、skyrim/hearthfireパッケージのmessages.phpにある、英語の翻訳文字列を上書きする必要がある場合、言語ファイルをlang/vendor/hearthfire/en/messages.phpへ置く必要があります。このファイルは、オーバーライドしたい翻訳文字列のみを定義します。オーバーライドしない翻訳文字列は、パッケージの元の言語ファイルから読み込まれます。So, for example, if you need to override the English translation strings in messages.php for a package named skyrim/hearthfire, you should place a language file at: lang/vendor/hearthfire/en/messages.php. Within this file, you should only define the translation strings you wish to override. Any translation strings you don't override will still be loaded from the package's original language files.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作