Two step view process

by Naneau

Most of you will be familiar with the problem that of every HTML page you generate, only a certain part changes from page to page. For instance, on this very website (which has been created using wordpress) only the posts differ from page to page. The head section is the same on every page, as is the sidebar.

In the comments for my posts on smarty as well as in #zftalk there is a recurring question about how to achieve this. There are basically two paths you can follow:

The first is to create views that include the different sections that stay the same using some kind of require. In smarty this would be done by the {include} tag. In Zend_View PHP syntax, it would be done with:

1
<?php $this->render('someTemplate.phtml'); ?>

This has the advantage of great control over what gets rendered where. It has a big disadvantage because there will be repetition. If you wanted to change the order in which things get included, you would have to change all your views. In general, repetition is bad.

The second approach is to do a “reverse include”. When writing controllers for your different pages, it makes sense to just render the bit that changes. You can then put the result into some kind of global template. This approach is called a “two step view“. If you just have a single repeating part, it’s incredibly easy to write a front controller plugin that gets the body out of the response object, render a global view, and put the result of that into the response.

There are a few schools of thought on this subject. While I believe in keeping things simple, sometimes a more complex approach is required. Sometimes not just a single part of the page changes, but multiple parts. Some applications have multiple global views, etcetera. Things will get out of hand quickly. Zend_Layout will address that, although I’ve been lead to believe that it will probably not make 1.0.

Update

It appears we will get a final way to do two-step-views/layouts in 1.1. Until then, I will redirect you to Spotsec’s site for a tutorial on [Xend/Zend]_view.