How to switch multi-language packages in yii2
1. Configuration components
'components' => [ 'i18n' => [ 'translations' => [ '*' => [ 'class' => 'yii\i18n\PhpMessageSource', //'basePath' => '/messages', 'fileMap' => [ 'app' => 'app.php', ], ], ], ], ]
2. Create the messages directory
Create the messages directory in the directory of the same level as the web. This directory stores the language configuration file
Create messages/zh-CN/app.php, zh-CN It is the language identifier (\Yii::$app->session['language'] = 'zh-CN', that is, configured as zh-CN language), and the language configuration array is stored in app.php (the name of app.php is configured by The 'app' option of the component is determined)
The following is the app.php file content
<?php return [ //常用 'Action' => '操作', 'Search' => '搜索', 'Reset' => '重置', ];
#3. To implement language switching
There are two Method:
a) Each controller needs to be initialized (write the init function). In the init function, it is mainly to assign a value to Yii::$app->language. For example: Yii::$app->language = 'zh-CN'.
b) In web/index.php (entry file), change the code to create the application to the following code
$application = new yii\web\Application($config); $application->language = isset(\Yii::$app->session['language']) ? \Yii::$app->session['language'] : 'en'; $application->run();
4. Write the controller method to implement language switching
public function actionLanguage(){ $language= \Yii::$app->request->get('lang'); if(isset($language)){ \Yii::$app->session['language']=$language; } //切换完语言哪来的返回到哪里 $this->goBack(\Yii::$app->request->headers['Referer']); }
To switch languages, just call this method with the 'lang' parameter!
For more tips on using Yii and website building tutorials, please pay attention to Website Building Tutorial.
The above is the detailed content of How to switch multi-language packages in yii2. For more information, please follow other related articles on the PHP Chinese website!