Changing Layout in ZF2 Controller

Published on November 15, 2015 by

Changing the layout or template within a Zend Framework 2 is easy. Thanks to the layout controller plugin, one can change the layout for a given controller action in just one line.

public function indexAction()
{
	$this->layout('layout/default');
	return new ViewModel();
}

As you can see above, the only thing you have to do in order to change the layout for a ZF2 controller action, is to pass in the name of the layout to the layout controller plugin. Afterwards, simply return a view model or array as usual.

Make sure that the name that you passed to the layout controller plugin is available within the view manager’s template map. Simply add it to one of your module’s module.config.php (by convention) so it looks like below.

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

Simply adjust to your particular needs.

Featured

Learn Zend Framework today!

Take an online course and become a ZF2 ninja!

Here is what you will learn:

  • Understand the theory of Zend Framework in details
  • How to implement an enterprise-ready architecture
  • Develop professional applications in Zend Framework
  • Proficiently work with databases in Zend Framework
  • ... and much more!
Zend Framework logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.