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.