Yii2 语言翻译机制

参考:Yii Framework 2.0 权威指南 - 高级专题(Special Topics) - 国际化(Internationalization)

注册 i18n 组件(config/main.php):

return [
    'language' => 'zh-CN',
    'components' => [
        'i18n' => [
            'translations' => [
                'app*' => [
                    'class' => 'yii\i18n\PhpMessageSource',
                    //'basePath' => '@app/messages',
                    //'sourceLanguage' => 'en-US',
                    'fileMap' => [
                        'app' => 'app.php',
                        'app/error' => 'error.php'
                    ]
                ]
            ],
        ],
    ],
];

语言包:

@app/messages目录下新建目录,目录名就是翻译的目标语言,例如:zh-CN;然后新建app.php文件:

return [
    'hello' => '你好',
];

调用翻译:

echo Yii::t('app', 'hello');  //return: '你好'