Home > Article > PHP Framework > How to set language switching in yii2
yii2 Set the method to switch languages: first configure the components; then create a messages directory in the web directory at the same level, which stores the language configuration file; then initialize each controller; finally write the controller method to implement Just switch the language.
##Yii2.0 realizes multi-language switching
Recommendation: "yii tutorial"
1. Configure components'components' => [ 'i18n' => [ 'translations' => [ '*' => [ 'class' => 'yii\i18n\PhpMessageSource', //'basePath' => '/messages', 'fileMap' => [ 'app' => 'app.php', ], ], ], ], ]2. Create messages directoryCreate messages in the same level directory of the web Directory, this directory stores the language configuration fileCreate messages/zh-CN/app.php, zh-CN is the language identifier (\Yii::$app->session['language'] = 'zh -CN' (that is, configured as zh-CN language), the language configuration array is stored in app.php (the name of app.php is determined by the 'app' option when configuring the component) The following is the content of the app.php file
<?php return [ //常用 'Action' => '操作', 'Search' => '搜索', 'Reset' => '重置', ];3. Implement language switchingThere are two methods:a:Need to initialize each controller (write the init function) , in the init function, it mainly assigns values 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, Implementing 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 achieve language switching, just call this method with the 'lang' parameter!
The above is the detailed content of How to set language switching in yii2. For more information, please follow other related articles on the PHP Chinese website!