common/config/main.php
'language' => 'zh-CN', //yii2默认使用‘en-US’若要设置中文可用
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@common/messages',
'sourceLanguage' => 'en-US',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
],
],
],
]
执行命令生成i18n设置文件
php yii message/config @common/config/i18n.php
return [
'color' => null,
'interactive' => true,
'help' => null,
'silentExitOnException' => null,
'sourcePath' => '@rootPath', //设置为项目跟地址,检索全项目 bootstrap:(Yii::setAlias('@rootPath', dirname(dirname(__DIR__)));)
'messagePath' => '@common/messages', //config设置的basePath,若无messages文件夹需要自己创建
'languages' => ['zh-CN'], //设置需要转换的语言
'translator' => 'Yii::t',
'sort' => false,
'overwrite' => true,
'removeUnused' => false,
'markUnused' => true,
'except' => [
'.svn',
'.git',
'.gitignore',
'.gitkeep',
'.hgignore',
'.hgkeep',
'/messages',
'/BaseYii.php',
'vendor', //排除依赖
],
'only' => [
'*.php',
],
'format' => 'php',
'db' => 'db',
'sourceMessageTable' => '{{%source_message}}',
'messageTable' => '{{%message}}',
'catalog' => 'messages',
'ignoreCategories' => [],
'phpFileHeader' => '',
'phpDocBlock' => null,
];
执行命令生成映射文件
php yii message @common/config/i18n.php
文件在common/messages/zh-CN/app.php
使用
Yii::t('app', 'This is a english message!')
动态更改返回中英文
//BaseController
public function beforeAction($action)
{
if (!Yii::$app->request->isOptions) {
if (Yii::$app->request->headers->get('language')) {
Yii::$app->language = Yii::$app->request->headers->get('language') ?: 'en-US';
}
}
return parent::beforeAction($action);
}
网友评论