phpzend-frameworkzend-framework2zend-framework-modules

Different layout file for different controller


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?


Solution

  • 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',
        ),
    ),