Thursday, June 10, 2010

Layout and Navigation, Part 1

This series of articles will cover a simple example of how to use Zend_Layout and Zend_Navigation for creating a 2-column template with a menu on the left side of the page. I'll be modifying the base application that gets installed by the quickstart. Let's get started.

The first thing we'll need is some content, and I'm going to use the simplest content possible for this example. So I'll create my ContentController.php and then add blank actions for an index plus 5 pages. The code looks like this:
class ContentController extends Zend_Controller_Action
{
public function indexAction() {}
public function page1Action() {}
public function page2Action() {}
public function page3Action() {}
public function page4Action() {}
public function page5Action() {}
}
And of course you need view scripts for each of these, set these up in /application/views/scripts/content and they'll be named page1.phtml, page2.phtml, etc. My content in each file is simply "This is page n." (where n is the page number) so that I can verify that the correct page is being pulled up. This should work immediately after creating the pages by going to your url, for example http://zendreflections/content/page1, so check this first.

Now that there's some rudimentary content, we'll add a simple layout to the site. Add Zend_Layout to the MVC by adding the following line to your index.php bootstrap file:
    /**
* Layout helper
*/
require_once 'Zend/Layout.php';
Zend_Layout::startMvc();
By default, Zend will look for a file named layout.phtml in the /application/views/scripts directory. For this example, let's put the layouts in a different directory, say /application/views/layouts. One way to do this is to add the following line to /application/configs/application.ini:
resources.layout.layoutPath = APPLICATION_PATH "/views/layouts"
So now we need a layout file (layout.phtml). Since this is a Zend article and not a css article, I'm going to grab my css from somewhere else, http://www.bluerobot.com/web/layouts/layout1.css (see how it looks here). This layout has Header, Content, and Menu divs. Here is the code:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Site
<link href="http://www.bluerobot.com/web/layouts/layout1.css" rel="stylesheet" type="text/css">
</head>
<body>

<div id="Header">My Site</div>

<div id="Content">
<?php
// fetch 'content' key using layout helper:
echo $this->layout()->content;
?>
</div>

<div id="Menu">
menu goes here
</div>

</body>
You see there is currently a placeholder for the menu. That's because we'll have to create it first using Zend_Navigation, which will be the subject for the next article.

Happy coding!

No comments:

Post a Comment