多余的话不说,直接看代码:
1) 在 common/config/main.php 写入配置代码
1 // 配置翻译信息 2 ‘i18n‘ => [ 3 ‘translations‘ => [ 4 ‘app‘ => [ 5 ‘class‘ => ‘yii\i18n\PhpMessageSource‘, 6 ‘basePath‘ => ‘@common/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) 配置完成,效果如下图
记忆力不好,记录下来
时间: 2024-10-14 13:18:19