Change layout template based on controller in Zend Framework 2

January 18, 2013

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


'view_manager' => array(
  //more options
 'template_map' => array(
    'layout/MyControllerName'=> PATH_TO_TEMPLATE

Step 2.

Add in module.php

  ->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])) {
}, 100);


Suggestions or problems ?

Write a comment.

tags: ,
posted in how to ?, php, Zend Framework 2 by Ivan Gospodinow

Follow comments via the RSS Feed | Leave a comment | Trackback URL

1 Comment to "Change layout template based on controller in Zend Framework 2"

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

Leave Your Comment

Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/c2kblate/sites/ on line 1048
Powered by Wordpress and MySQL. Theme by Shlomi Noach,