问题描述
我可以在哪里设置全局语言(基于用户的 cookie)?如何让它在整个应用程序(控制器、视图等)中工作?
Where can I set language (based on user's cookie) globally? How to make it work in the whole application (controllers,views, etc.) ?
在文档中我找到了 Yii::$app->language = '';
但是,我可以在哪里编写逻辑以正确的方式更改语言?
In documentation I found Yii::$app->language = '';
but, where I can write my logic to change the language in right way?
推荐答案
你应该使用
Yii::$app->language = '';
在所有控制器的父级控制器中.父类应该在 components 文件夹中,如果它不可用,则使用类似
inside the controller that is parent to all your controllers. The parent class should be inside the components folder, and if it is not available than create the component with something like
use yiiwebController;
class MyController extends Controller
{
public function init()
{
parent::init();
#add your logic: read the cookie and then set the language
}
}
在那之后,你必须确保你的所有控制器都扩展了你新创建的 MyController 而不是原来的.
After that, you have to be sure that all your controllers extends your newly created MyController instead of the original one.
希望能帮到你.
这篇关于在 Yii2 应用程序中设置全局语言值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!