In Zend Framework 2 , layout can be easily changed from module based on controller(name).
Step 1.
Add in module.config.php file
'controller_layouts' => array( 'MyControllerName' => 'layout/MyControllerName', ),
and
'view_manager' => array( //more options 'template_map' => array( 'layout/MyControllerName'=> PATH_TO_TEMPLATE ), ),
Step 2.
Add in module.php
$e->getApplication()->getEventManager()->getSharedManager() ->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) { $controller = $e->getTarget(); $controllerClass = get_class($controller); $ar = explode('\\',$controllerClass); $controllerStr = str_replace('Controller','',$ar[count($ar) -1]); $config = $e->getApplication()->getServiceManager()->get('config'); if (isset($config['controller_layouts'][$controllerStr])) { $controller->layout($config['controller_layouts'][$controllerStr]); } }, 100);
Suggestions or problems ?
Write a comment.
Adrian wrote:
Thank you so much! It worked perfectly! 🙂 I have an AdminController in my project that would use a different layout and your post is exactly what I needed. Got tired of specifying the layout in every damn action of the Controller. It just felt inappropiate to do that over and over again.
Link | May 15th, 2014 at 10:52