[TOC]
#### 1. Yii::t() 方法可以像这样使用,如下所示:
~~~
//代码片段中,'app' 代表文本消息的类别
echo \Yii::t('app', 'This is a message to translate!');
~~~
#### 2. 修改配置文件
~~~
'components' => [
// ...
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@common/messages',
//'sourceLanguage' => 'en',
'fileMap' => [
'common' => 'common.php',
'backend' => 'backend.php',
'frontend' => 'frontend.php',
],
],
],
],
],
~~~
> 上面配置中的“*”表示所有消息开始程式类别必须使用这种特殊的消息源进行翻译(转换)。
设置了fileMap进行对应各自的源消息。如\Yii::t(''backend, 'username'),翻译中文时,则对应common文件夹->messages文件夹->zh文件夹->backend.php源文件
#### 3. 设置翻译文件
>上一步骤的配置文件中,我们设置了basePath。所以翻译文件应存放在:
>>common
>>>messages
>>>>es
>>>>ru
>>>>zh
>>>>>backend.php
>>>>>common.php
>>>>>frontend.php
~~~
return [
'This is a string to translate' => '这是一个翻译的字符串'
];
?>
~~~
#### 4. 文本消息翻译 测试。
~~~
//测试111111
public function actionTest1() {
//该文本消息会被翻译成中文,因为设定的目标语言是 zh-CN。我们也可以动态地改变应用程序的语言。
echo \Yii::t('backend', 'This is a string to translate');
\Yii::$app->language = 'en-US';
echo \Yii::t('backend', 'This is a string to translate!');
}
//测试222222
//在一个转换(翻译)的消息,可以插入一个或多个参数
public function actionTest2() {
$username = 'Username1';
// display a translated message with username being "Vladimir"
echo \Yii::t('backend', 'Hello, {username}!', [
'username' => $username,
]), "
";
$username = 'username2';
// display a translated message with username being "John"
echo \Yii::t('backend', 'Hello, {username}!', [
'username' => $username,
]), "
";
$price = 150;
$count = 3;
$subtotal = 450;
echo \Yii::t('backend', 'Price: {0}, Count: {1}, Subtotal: {2}', [$price, $count, $subtotal]);
}
~~~
#### 5. 视图文件翻译 测试
> 可以翻译整个视图脚本,而不是单独的翻译文本消息。例如,如果目标语言是zh-CN,想翻译是 views/site/index.php 视图文件,
那么应该翻译视图并保存在 views/site/zh-CN 目录下。
第8步 - 创建 views/site/zh-CN 目录。
然后,zh-CN 文件夹中创建一个 index.php 文件并使用下面的代码。
~~~
/* @var $this yii\web\View */
$this->title = 'My Yii Application';
?>
欢迎您访问!
~~~
> 更多可参考
>>1. http://www.yiifans.com/yii2/guide/tutorial-i18n.html
>>1. http://www.yiibai.com/yii2/yii_localization.html