[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
~~~
<?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,
]), "<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]);
}
~~~
#### 5. 視圖文件翻譯 測試
> 可以翻譯整個視圖腳本,而不是單獨的翻譯文本消息。例如,如果目標語言是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>
~~~
> 更多可參考
>>1. http://www.yiifans.com/yii2/guide/tutorial-i18n.html
>>1. http://www.yiibai.com/yii2/yii_localization.html
- 基礎教程
- 入門安裝
- Yii2 composer 安裝慢解決
- Cookies
- 數據庫操作
- 數據提供者
- 助手類
- 驗證規則
- GridView
- DetailView
- YII2分頁
- JS、CSS的引用
- Excel導出
- 中文轉拼音
- 發送郵件
- 第三方插件
- Session跨域共享
- Url跨域訪問
- 場景應用
- 查詢條件鏈
- Session分布式共享
- Redis的使用
- mongodb
- 高級教程
- 自定義gii模板
- 角色權限管理(RBAC)
- user組件的配置
- 國際化(I18N)
- 小部件(Widget)
- 模塊(Module)
- 行為(Behavior)
- 緩存(Cache)
- migrate 數據庫遷移
- phpstorm
- 快捷鍵
- 自定義
- 其它插件