在调度事件上访问 ViewModel 变量 [英] Access ViewModel variables on dispatch event
问题描述
这是一个 ZF2 问题.
This is a ZF2 question.
我正在尝试更改我的模板,具体取决于我的控制器上设置的变量(因为我将决定使用哪个模板).在我的 onBooststrap 模块中,我有:
I'm trying to change my template, depending on a variable setted on my controller (since is there that im going to decide which template use). In my module onBooststrap i have:
$this->eventManager->attach('dispatch', function($e)
{
if (0 === strpos($e->getRouteMatch()->getParam('controller'), __NAMESPACE__, 0))
{
$e->getViewModel()->setTemplate('layout');
}
}, -100);
在我的控制器中:
class IndexController extends AbstractActionController
{
public function indexAction ()
{
$view = new \Zend\View\Model\ViewModel();
$view->setVariable("layout", "layout");
return $view;
}
}
但是,我如何访问该视图变量布局",以便我可以在 setTemplate 的调度事件中更改它?
but, how do i get access to that view variable "layout", so i can change it in the dispatch event on setTemplate?
推荐答案
查看 onDispatch
方法和 MvcEvent
类似乎有一个 getResult()
方法,这可能包含控制器操作的结果.
Looking at the onDispatch
method and the MvcEvent
class it seems there is a getResult()
method, this may contain the result from the controller action.
否则你有没有看过布局控制器插件?此插件将允许您更改模板:
Otherwise have you looked at the layout controller plugin? This plugin would allow you to change the template:
$this->layout('new layout');
当然,这需要在控制器内部,而且很可能需要将模板添加到模板映射中.
Of course this would need to be inside the controller and most likely require adding the template into the template map.
这篇关于在调度事件上访问 ViewModel 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!