[Yii2] i18n(Internationalization) – 語系架構設定範例 (使用Key對應架構)

Intro

官網文件:Internationalization

語系代碼:[i18n] 淺談Internationalization - Language Identifiers (RFC 3066)


架構範例

別於官網以主要語系(英文)為sourceLanguage,本章範例以Key的架構去定義語系(也就是Message是指定一個Key必經轉譯)。

Configuration

return [
    // set target language to be English
    'language' => 'en-US',

    // set source language to be a customized key which means it will always translate.
    'sourceLanguage' => 'key',

    'components' => [
        'i18n' => [
            'translations' => [
                'app*' => [
                    'class' => 'yii\i18n\PhpMessageSource',
                    //'basePath' => '@app/messages',
                    //'sourceLanguage' => 'key',
                    'fileMap' => [
                        'app' => 'app.php',
                        'app/error' => 'error.php',
                    ],
                ],
            ],
        ],
    ],
];

Message Translation

接著在@app/messages目錄下創建指定語系資料夾,依照設定'app'=>'app.php'所以產生app.php語系檔,範例@app/messages/en-US/app.php

<?php

return [
    'test' => 'Test',
];

在實作Message呈現時,例如在View:

<?=\Yii::t('app', 'test');?>

Leave a Reply

Your email address will not be published. Required fields are marked *