Zend Framework: How to Build a Dynamic Layout by Setting Variables in your Controllers CodeUnit 04 APR 2011

I have a Zend Framework website that is broken up into modules. Accordingly, I want my single layout.phtml Layout script to dynamically change ever so slightly depending on what module or rather controller I hit – in my case change the header image. So how do we do this?

Well the first thing is gaining access to the Layout object so that you can set some variables in this.

To gain access within action controllers, use the layout() action helper:

// Calling helper as a method of the helper broker:
$helper = $this->_helper->getHelper('Layout');
$layout = $helper->getLayoutInstance();

To gain access within view scripts, use the layout() view helper:

$layout = $this->layout();

To gain access via the bootstrap, retrieve the layout resource:

$layout = $bootstrap->getResource('Layout');

Finally if you still can’t get a layout object to work with, use the static method (not entirely recommended):

$layout = Zend_Layout::getMvcInstance();

Now that you have a $layout object to work with, you’ll probably want to assign some sort of variable value to it in order to dynamically affect your layout.phtml file. To set a variable you can either directly assign with the = operator or make use of the assign() method:

// Setting content:
$layout->somekey = "foo"
// Using the assign() method:
$layout->assign('someotherkey', 'bar');

Okay, now that we have a variable stored in the layout object, it becomes trivial to make our layout dynamic. For example, having previously added a value to $layout->mainheaderlogo = ‘image1.png’, we can now add the following to our layout.phtml file:

<div id=”logobanner”><a href=”/”><img src=”/images/<?php echo $this->layout()->mainheaderlogo; ?>” /></a></div>

And now you know. Nifty.

(Update: Or you should probably really learn to use Zend View Placeholders correctly, as they are the correct way of making your layout more Dynamic!!)

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.