Different layout file for different controller

蓝咒 提交于 2019-11-29 10:24:38

问题


How to make my ZF2 module load other layout file for specific controller ?

Consider you have IndexController and AdminController in your ZF2 application module and the IndexController is using layout.phtml but you want to use adminlayout.phtml for AdminController.

How is it possible?


回答1:


class Module {
    public function onBootstrap($e) {
        $em  = $application->getEventManager();

        $em->attach(MvcEvent::EVENT_DISPATCH, function($e) {
            $controller = $e->getTarget();
            if ($controller instanceof Controller\AdminController) {   
                $controller->layout('layout/layoutadmin.phtml');
            } else {
                $controller->layout('layout/layout.phtml');
            }   
        });
    }
}

and don't forget to register your new controller by adding this config in your module config file:

'controllers' => array(
    'invokables' => array(
        'Application\Controller\Index' => 'Application\Controller\IndexController',
        'Application\Controller\Admin' => 'Application\Controller\AdminController',
    ),
),



回答2:


other best Solution :

'view_manager' => array(
        'template_path_stack' => array(
            'YOURMODULENAME' => __DIR__ . '/../view',
        ),

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

change YOURMODULENAME to your module specific name




回答3:


Rather than adding logic to your entire module in the onBootstrap method, you can use your controller's onDispatch method to simply set the layout for that entire controller.

In your admin controller, add a shortcut at the top:

use Zend\Mvc\MvcEvent;

Then, use the following onDispatch in your controller:

public function onDispatch(MvcEvent $mvcEvent)
{   
    $this->layout()->setTemplate('layout/admin');

    return parent::onDispatch($mvcEvent);
}

I believe this solution is better because the code only gets called when the admin controller is called.



来源:https://stackoverflow.com/questions/11921329/different-layout-file-for-different-controller

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