1. 程式人生 > >Yii2.0 語言切換的簡單設置

Yii2.0 語言切換的簡單設置

control get out menuitem 根據 site cti http 文件

多余的話不說,直接看代碼:

1) 在 common/config/main.php 寫入配置代碼

 1 //        配置翻譯信息
 2         ‘i18n‘ => [
 3             ‘translations‘ => [
 4                 ‘app‘ => [
 5                     ‘class‘ => ‘yii\i18n\PhpMessageSource‘,
 6                     ‘basePath‘ => [email protected]/messages‘,
 7
// ‘sourceLanguage‘ => ‘en‘, 8 ‘fileMap‘ => [ 9 ‘app‘ => ‘app.php‘, 10 ‘app/error‘ => ‘error.php‘, 11 ], 12 ], 13 ], 14 ],

2) 前臺模板文件要寫出切換的地址 frontend/views/layouts/main.php

1  $menuItems = [
2         [‘label‘ => ‘Home‘, ‘url‘ => [‘/site/index‘]],
3         [‘label‘ => ‘About‘, ‘url‘ => [‘/site/about‘]],
4         [‘label‘ => ‘Contact‘, ‘url‘ => [‘/site/contact‘]],
5         [‘label‘ => Yii::t(‘app‘,‘Chinese‘), ‘url‘ => [‘/site/language‘,‘lang‘=>‘zh_CN‘]],
6
[‘label‘ => Yii::t(‘app‘,‘English‘), ‘url‘ => [‘/site/language‘,‘lang‘=>‘en‘]], 7 ];

3) 根據模板傳入的參數在控制器中寫入代碼 frontend/controllers/SiteController.php

1  //語言切換
2     public function actionLanguage(){
3         $language=  Yii::$app->request->get(‘lang‘);
4         if(isset($language)){
5             Yii::$app->session[‘language‘]=$language;
6         }
7         //切換完語言哪來的返回到哪裏
8         $this->goBack(Yii::$app->request->headers[‘Referer‘]);
9     }

4) 根據配置創建文件路徑 common/messages/en/app.php

return [
    ‘English‘=>‘English‘,
    ‘Chinese‘=>‘Chinese‘,
];

common/messages/zh_CN/app.php

return [
    ‘English‘=>‘英文‘,
    ‘Chinese‘=>‘中文‘,
];

5) 配置完成,效果如下圖

技術分享

技術分享

記憶力不好,記錄下來

Yii2.0 語言切換的簡單設置