Benjamin Tigano Developer at Large

Using alternate layouts

So we've got our basic Zend MVC application using a layout so that we can consolidate the output of  sections like headers, footers, etc. that likely won't change much from page to page, rather than calling those sections from every view script. In our project, we have one layout, layout.phtml, but what if we wanted to have two or more different layouts, depending upon some other variable? This is easily done using the layout() ViewHelper.

First, let's create a new layout file in application/layouts/scripts. I called mine alternate.phtml. To keep things simple, I just copied the default layout.html, and then removed the majority so I'm left with this:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<!-- start page -->
<div id="page">
	<!-- start content -->
	<div id="content">
		<?php echo $this->layout()->content; ?>
	</div>
	<!-- end content -->
	<br style="clear: both;" />
</div>
<!-- end page -->
</body>
</html>

The idea is just to make it different so that we can prove that we're in fact using the other layout.
Next, since we only have one controller (index), and one action (index), let's make another action in the IndexController (don't forget to also add in the view script for it, too.) We'll use this other action to render the alternate layout. To do that, we'll grab the layout ViewHelper, and then call the setLayout method, passing in the name of the layout we want to use. Because I called my layout alternate.phtml, I'll pass in 'alternate'. Here is my full alternateAction method that I created in the IndexController.

public function alternateAction()
{
    $layout = $this->_helper->layout();
    $layout->setLayout('alternate');
}

Now when I navigate to http://localhost/index/alternate, I should be seeing that other layout. You should also visit http://localhost/index just to make sure that the index action is still using the other, default layout that we originally started with.

That wraps up this section. Pretty easy, right? If not, leave your questions in the comments section below.

Download the project

Next up, we'll be adding logging capabilities to our application!

Fork me on GitHub