A free and open-source book on ZF3 for beginners


6.4. Switching between Layouts

By default, ZF3 provides you with a single layout template layout.phtml. In real-life applications, you will probably need to have several layouts and switch the layout for certain controller/action.

For example, you may have a front-end and a back-end part of your site. The front-end part would consist of web pages publicly visible to all users and would utilize the default layout for all of these pages. The back-end part would consist of pages visible to the administrator user only and utilize another layout template containing the administrative menu.

First, prepare another layout template file. For example, call it layout2.phtml. To simplify the file preparation, copy the content of the default layout.phtml file and make the necessary changes.

When the second layout template is ready, you can switch between layouts for a particular controller's action by using the following code:

// A controller's action method that uses an alternative
// layout template.
public function indexAction() 
{
  //...

  // Use the Layout plugin to access the ViewModel
  // object associated with layout template.
  $this->layout()->setTemplate('layout/layout2');
  
  //...
}

In the example action method above, we use the Layout controller plugin (line 9) that allows to access the instance of the ViewModel class associated with the layout template. To change the layout template for this particular action method, we called the setTemplate() method provided by the ViewModel class.

In addition to the Layout controller plugin, there is the Layout view helper which provides the same capabilities. With the Layout view helper, you can, for example, switch layout from the "static" page which has no specific controller action.

6.4.1. Setting Layout for All Actions of a Controller

If all action methods of a controller class need to use the same alternative layout, you can override the onDispatch() method of the AbstractActionController class and call the setTemplate() method there, as shown in the example below:

// Add this alias in the beginning of the controller file
use Zend\Mvc\MvcEvent;

// ...

class IndexController extends AbstractActionController 
{
  /** 
   * We override the parent class' onDispatch() method to
   * set an alternative layout for all actions in this controller.
   */
  public function onDispatch(MvcEvent $e) 
  {
    // Call the base class' onDispatch() first and grab the response
    $response = parent::onDispatch($e);        
	
    // Set alternative layout
    $this->layout()->setTemplate('layout/layout2');                
	
    // Return the response
    return $response;
  }
}

Top