Accessing the Layout Object
On occasion, you may need direct access to the layout object. There are three ways you can do this:
-
Within view scripts: use the layout() view helper, which returns the Zend_Layout instance registered with the front controller plugin.
-
<?php $layout = $this->layout(); ?>
Since it returns the layout instance, you can also simply call methods on it, rather than assigning it to a variable.
-
-
Within action controllers: use the layout() action helper, which acts just like the view helper.
-
// Calling helper as a method of the helper broker:
-
$layout = $this->_helper->layout();
-
-
// Or, more verbosely:
-
$helper = $this->_helper->getHelper('Layout');
-
$layout = $helper->getLayoutInstance();
As with the view helper, since the action helper returns the layout instance, you can also simply call methods on it, rather than assigning it to a variable.
-
-
Elsewhere: use the static method getMvcInstance(). This will return the layout instance registered by the bootstrap resource.
-
$layout = Zend_Layout::getMvcInstance();
-
-
Via the bootstrap: retrieve the layout resource, which will be the Zend_Layout instance.
-
$layout = $bootstrap->getResource('Layout');
Anywhere you have access to the bootstrap object, this method is preferred over using the static getMvcInstance() method.
-
Other Operations
In most cases, the above configuration and layout script (with modifications) will get you what you need. However, some other functionality exists you will likely use sooner or later. In all of the following examples, you may use one of the methods listed above for retrieving the layout object.
-
Setting layout variables. Zend_Layout keeps its own registry of layout-specific view variables that you can access; the $content key noted in the initial layout script sample is one such example. You can assign and retrieve these using normal property access, or via the assign() method.
-
disableLayout(). Occasionally, you may want to disable layouts; for example, when answering an Ajax request, or providing a RESTful representation of a resource. In these cases, you can call the disableLayout() method on your layout object.
-
$layout->disableLayout();
The opposite of this method is, of course, enableLayout(), which can be called at any time to re-enable layouts for the requested action.
-
-
Selecting an alternate layout: If you have multiple layouts for your site or application, you can select the layout to use at any time by simply calling the setLayout() method. Call it by specifying the name of the layout script without the file suffix.
-
// Use the layout script "alternate.phtml":
-
$layout->setLayout('alternate');
The layout script should reside in the $layoutPath directory specified in your configuration. Zend_Layout will then use this new layout when rendering.
-