Categories


Archives


Recent Posts


Categories


Adding Custom Layout Handles in Magento 2

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

Thanks to Magento 2’s MVVM approach the traditional responsibilities of a controller object have been pushed into the “view model” layer (i.e. a block’s _prepareLayout method).

The main job a controller performs in Magento 2 is to

  1. Determine what sort of response is needed (HTML page, JSON, Redirect)
  2. Create an object to handle that response
  3. Return that object to the system for processing

For a standard HTML page, this means injecting a page factory object in your controller’s constructor

public function __construct(
    Context $context,
    PageFactory $resultPageFactory
) {
    $this->resultPageFactory = $resultPageFactory;
}

and using that factory to return an object in the controller’s execute method.

$resultPage = $this->resultPageFactory->create();
return $resultPage;

One benefit of this is, it’s pretty easy to add custom layout handles to your response. Every page object has an addHandle method

$resultPage = $this->resultPageFactory->create();
$resultPage->addHandle('my_custom_handle');
return $resultPage;

and your response will include the additional handle. This was possible in Magento 1, but required redefining a specific controller action method in your controller, and making sure you included a call to the parent method. It’s not an earth shattering improvement, but its something that makes life a little easier for module developers.

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 17th March 2016

email hidden; JavaScript is required