Home> PHP Framework> YII> body text

How to set language switching in yii2

藏色散人
Release: 2020-07-20 10:15:39
Original
2674 people have browsed it

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.

How to set language switching in yii2


##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', ], ], ], ], ]
Copy after login

2. Create messages directory

Create messages in the same level directory of the web Directory, this directory stores the language configuration file

Create 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

 '操作', 'Search' => '搜索', 'Reset' => '重置', ];
Copy after login

3. Implement language switching

There 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();
Copy after login

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']); }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!