Register An Observer & Add Layout Handles In Magento 2
Often, you may need to add layout handles to a page. The way I would approach this is by utilising an Observer.
The event we will want to listen to needs to have the layout passed as a parameter, also we need to make sure that layout XML isn’t generated yet. The perfect event for this is in the method Magento\Framework\View\Layout\Builder::loadLayoutUpdates():
As you can see, this fires an event attaching data, which is the action name of the request and the layout module which is an implementation of View\LayoutInterface.
In Magento 1.x to register an observer you would define some XML in config.xml, however now we should add our event definition within etc/events.xml, this is how our file should look:
Next we must create an observer class, in Magento 1.x we typically had one observer class in Model/Observer.php. However I like the idea of having my observers in an Observer directory within my directory.
Your observer should implement the ObserverInterface, here is what that interface looks like at the time of writing this article:
Just like with controllers, each observer must implement a execute() method which is automatically called, so this is where your main logic should go.
Here is what a very basic example would look like of an Observer which adds layout handles to the page:
That should be it, you now have added a custom layout handle to the page. Obviously you would have some logic in regarding when you want your layout handle added, for instance like checking if your extension is enabled.