Yii2如何将模型实例传递到主布局? [英] Yii2 How to pass the model instance to the main layout?

查看:106
本文介绍了Yii2如何将模型实例传递到主布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个更改密码引导程序模式,当用户单击更改密码"导航栏菜单时会触发该模式.

I have a change password bootstrap modal which will get triggered when the user clicks on the Change password navBar menu.

我已将模式包含在页脚中.但是,如何将ChangePassword model instance传递到页脚布局文件?

I have included the modal in the footer. But how can I pass the ChangePassword model instance to the footer layout file?

可以使用beforeRender Or EVENT_BEFORE_RENDER吗?如果是,怎么办?

Can beforeRender Or EVENT_BEFORE_RENDER be used? If yes, How?

按照建议,我将以下代码放在common/config/bootstrap.php中:

As suggested, I have put the following code in common/config/bootstrap.php:

yii\base\Event::on(yii\base\View::className(), yii\base\View::EVENT_BEFORE_RENDER, function() {
    $modelChangePassword = new frontend\models\ChangePassword;
    $this->view->params['modelChangePassword'] = $modelChangePassword;
});

但是它给出了Using $this when not in object context错误.

推荐答案

您可以通过查看 参数:

在呈现视图之前将其添加到控制器中

Add this in controller before rendering view:

$this->view->params['model'] = $model;

...

$this->render(...); // this will render your view including main layout

然后在这样的视图中使用:

Then use in view like that:

$model = $this->params['model'];

更新:

如果要在所有应用程序控制器中全局使用它,则可以使用事件:

If you want it globally for all application controllers you can use events:

use Yii;
use yii\base\Event;
use yii\web\View;

...

Event::on(View::className(), View::EVENT_BEFORE_RENDER, function() {
    ...

    Yii::$app->view->params['model'] = $model;
});

将此代码放入应用程序引导程序或例如公共父控制器中.

Put this code in application bootstrap or for example in common parent Controller.

官方文档:

  • Events
  • Event::on()

这篇关于Yii2如何将模型实例传递到主布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆