Zend Framework 2 alternative layout template changed in module.php level

I am sure people are finding the correct way to handle this, but I keep ending up at older ZF2 how-to sites on Google searches that have incorrect ways to solve this, when there is more current and better information available now to change a layout template at the module level. In my case, I just wanted to do some testing and swap the layout at the module level to override the default set in config. It was simple actually, but thought I’d share what I did in case others end up finding older information.

Make sure you have the alt_layout.phtml file you need, of course. In the MVC Module.php onBootstrap():

$this->view = $e->getViewModel();
if($maybe_i_want_some_alt_layout == true){


The above snippet will override the entire module default template.  In my case, I wanted to quickly swap out the template to view differently on an iPad, so I used a check for that, then swapped the layout.  There are better, fancier, more clever, or I guess maybe more “ZF2-friendly” ways to do this, but this was simple solution for my use.

I can still override at the controller level manually if needed. Use this in the actual controller pre dispatch (if setup that way) or in the action. But this is not very flexible. I just had need for a specific action to show a special layout.