Change layout in the controller of Zend Framework 2.0

前端 未结 5 1093
旧巷少年郎
旧巷少年郎 2020-12-10 00:57

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

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


        
相关标签:
5条回答
  • 2020-12-10 01:24

    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'
        ),
    ),
    
    0 讨论(0)
  • 2020-12-10 01:24
    public function someAction() {
        $layout = $this->layout();
        $layout->setTemplate('layout/custom');
        $viewModel = new ViewModel();
        return $viewModel;
    }
    
    0 讨论(0)
  • 2020-12-10 01:25

    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).

    0 讨论(0)
  • 2020-12-10 01:30

    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');
    }
    
    0 讨论(0)
  • 2020-12-10 01:45

    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',
                ),
            ),
        ),
    
    0 讨论(0)
提交回复
热议问题