The default Magento 2 layout can’t be enough to create an attractive and eye-catching storefront. The layout must be in accordance with the business and customer type that helps in gaining more traffic and help in conversion.
However, to change the layout you need to follow the below solution. I have posted this method to update layout using observer in Magento 2 store.
Method to Update Layout Using Observer in Magento 2:
- Create events.xml file at path [Vendor]\[Module]\etc\frontend\events.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="layout_load_before"> <observer name="custom_layout" instance="[Vendor]\[Module]\Observer\UpdateLayoutObserver" /> </event> </config>
2. Create UpdateLayoutObserver.php file at path [Vendor]\[Module]\Observer\UpdateLayoutObserver.php
<?php namespace [Vendor]\[Module]\Observer; use Magento\Framework\Event\ObserverInterface; use [Vendor]\[Module]\Helper\Data; use Magento\Framework\Event\Observer; class UpdateLayoutObserver implements ObserverInterface { protected $helper; public function __construct ( Data $data ) { $this->helper = $data; } public function execute(Observer $observer) { $layout = $observer->getData('layout'); $currentHandles = $layout->getUpdate()->getHandles(); if (!in_array('default', $currentHandles)) { return $this; } $layout->getUpdate()->addHandle('custom_layout'); return $this; } }
3. Create custom_layout.xml file at path [Vendor]\[Module]\view\frontend\layout\custom_layout.xml
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="before.body.end"> <block class="Magento\Framework\View\Element\Template" name="custom_file" template="[Vendor]_[Module]::custom.phtml"/> </referenceContainer> </body> </page>
4. Create custom.phtml file at path [Vendor]\[Module]\view\frontend\templates\custom.phtml
<span> your code/design </span>
That’s it.
Follow these steps and update the layout of Magento 2 store pages easily.
Feel free to share the solution with fellow developers via social media.
Thanks.