I am trying to change a page layout before the loading of a page in Magento 2.

I want this layout to be loaded on the base of the configuration.

If you have any example available feel free to drop it in the answer section.


You can do it using observer.

layout_load_before this event means change layout before the pages load.

create 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="layout_load_before_abc" instance="Verndor\ModuleName\Observer\AddHandle" />

Now create an Observer/AddHandle.php

namespace Verndor\ModuleName\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\View\LayoutInterface;
use Verndor\ModuleName\Helper\Data;
class AddHandel implements ObserverInterface
    private $helper;
    public function __construct(
        Data $helper
    ) {
        $this->helper = $helper;
    public function execute(Observer $observer)
            $layout = $observer->getEvent()->getLayout();
       if ($this->helper->moduleEnabled()) {
           $layout->getUpdate()->addHandle("xyz_index_index"); //Name of layout_file_name.xml
       } else {
           $layout->getUpdate()->addHandle("abc_index_index"); //Name of layout_file_name.xml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.