1

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 configuration. If you have any example available feel free to drop it in the answer section

1

You can do it using observer.

layout_load_before this event means change layout before the pages load.

create etc/event.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\AddHandel" />
    </event>
</config>

Now create an Observer/AddHandel.php

    <?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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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