15 July 2009

Adding a Layout to your Zend Application

Using a layout in Zend is called a two step view. That's because it has a view for the layout file and a view for the content specific to the url request. How do we add a layout to our Zend application? Easy. Firstly, we need to add it to our application.ini to ensure that it is loaded by Zend_Application.

resources.layout.layoutPath = APPLICATION_PATH "/views/layouts"
resources.layout.layout = "layout"

This basically sets up the path and filename for the layout file. Note that some people would use APPLICATION_PATH "/layouts/scripts" as the layout's path, but I like it more in my views directory. Personal preference.

Next step is to make the layout file. But first there is something you can do to enhance your layout file. That is to set some default values in the bootstrap file. Let's look at that first.

 function _initViewHelpers()
  $layout = $this->getResource('layout');
  $view = $layout->getView();  
  $view->addHelperPath(APPLICATION_PATH . '/views/helpers', 'Zend_View_Helper'); 

All that you need to be concerned about there is the two settings we give to Zend's view. the ->doctype and ->helperPath. The doctype will be automatically generated by Zend, and the helperPath informs Zend where to look for helpers you are using for Zend's view. But I won't be covering view helpers in this article.

Now we can look at the layout file.

doctype() ?>

 headTitle($this->title) ?>
 headMeta()->appendHttpEquiv('Content-Type', 'text/html; charset=utf-8') ?> 

layout()->content ?>

The very first line pulls in the doctype declared in the bootstrap file, and the only other thing you should be looking at is the layout()->content ?> which is where the content from the request will be put in. So let's quickly make the content for the home page and then I'll explain some more.

class IndexController extends Zend_Controller_Action
 public function indexAction()
     $this->view->title = 'The title of the page here';

All it does is that it assigns a variable called 'title' to the Zend's view with a value which is a string. Next let's look at the view script for this action.


title ?>

and other content

Here we use echo out the value of the variable 'title', which we assigned to it in the controller. Viewing our application with a layout the page looks like this:

ZendWeaves Zend Layout

Take care!


No comments:

Post a Comment