// 代码片段中,'app' 代表文本消息的类别
echo \Yii::t('app', 'This is a message to translate!');
'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源文件
上一步骤的配置文件中,我们设置了basePath。所以翻译文件应存放在:
│──backend
│──common
│ │──messages
│ │──es
│ │──ru
│ │──zh
│ │──backend.php
│ │──common.php
│ │──frontend.php
│──frontend
<?php
return [
'This is a string to translate' => '这是一个翻译的字符串'
];
?>
//测试 A
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!');
}
//测试 B
//在一个转换(翻译)的消息,可以插入一个或多个参数
public function actionTest2() {
$username = 'Username1';
// display a translated message with username being "Vladimir"
echo \Yii::t('backend', 'Hello, {username}!', [
'username' => $username,
]), "<br>";
$username = 'username2';
// display a translated message with username being "John"
echo \Yii::t('backend', 'Hello, {username}!', [
'username' => $username,
]), "<br>";
$price = 150;
$count = 3;
$subtotal = 450;
echo \Yii::t('backend', 'Price: {0}, Count: {1}, Subtotal: {2}', [$price, $count, $subtotal]);
}
可以翻译整个视图脚本,而不是单独的翻译文本消息。例如,如果目标语言是zh-CN,想翻译是 views/site/index.php 视图文件, 那么应该翻译视图并保存在 views/site/zh-CN 目录下。 第8步 - 创建 views/site/zh-CN 目录。 然后,zh-CN 文件夹中创建一个 index.php 文件并使用下面的代码。
<?php
/* @var $this yii\web\View */
$this->title = 'My Yii Application';
?>
<div class = "site-index">
<div class = "jumbotron">
<h1>欢迎您访问!</h1>
</div>
</div>
(完)