Change layout in the controller of Zend Framework 2.0

ぃ、小莉子 提交于 2019-12-17 19:13:08

问题


I am learning ZF2.0 beta. In ZF1 we can change layout on the fly in controller:

Zend_Layout::getMvcInstance()->setLayout('layoutname');

But in ZF2.0 Zend\Layout class doesn't has method getMvcInstance(). I think that it can be made using dependency injections but not sure.


回答1:


The ZF2 is heavily under development and no guarantee can be made the way it works now, will be the way it works when ZF2 reaches a stable state.

However, the new view layer from Zend\Mvc is recently merged so you should be able to do this now (with current master):

public function somethingAction () 
{
    // Do some intelligent work

    $this->layout('layout/different');
}



回答2:


The best way I've found to set templates in actions is like this

public function someAction() {
    $viewModel = new ViewModel();
    $viewModel->setTemplate('layout/custom');

    return $viewModel;
}

In your module.config.php make sure you've set your appropriate template_map path.

    'view_manager' => array(
    'template_map' => array(
        'layout/custom' => __DIR__ . '/../view/layout/custom.phtml'
    ),
),



回答3:


public function someAction() {
    $layout = $this->layout();
    $layout->setTemplate('layout/custom');
    $viewModel = new ViewModel();
    return $viewModel;
}



回答4:


You will also have to set the layout either in the bootstrap or when using di. Di example:

    'Zend\View\Resolver\TemplateMapResolver' => array(
        'parameters' => array(
            'map'  => array(
            'layout/different' => __DIR__ . '/../view/layout/different.phtml',
            ),
        ),
    ),



回答5:


I have tried the above tips.

public function somethingAction () 
{
    // Do some intelligent work

    $this->layout('layout/different');
}

I got the correct result with this snippet.

public function someAction() {
    $viewModel = new ViewModel();
    $viewModel->setTemplate('layout/custom');

    return $viewModel;
}

It fetched both layouts(default & current module).



来源:https://stackoverflow.com/questions/9112766/change-layout-in-the-controller-of-zend-framework-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!