Magento 2 : Add A Custom Layout Using Observer

Sometimes we need to display a specific page / category with a different layout. We are going to see how we can achieve it 🙂

Let’s say that we have to change the layout for a specific category called : “shop” (Here the condition is on the category name, a better way would be to check the category Id though)

app/code/MyNamespace/MyModule/etc/frontend/events.xml
<?xml version="1.0" encoding="UTF-8"?>

<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="add_custom_layout" instance="MyNamespace\MyModule\Observer\AddCustomLayoutUpdateHandle"/>
    </event>
</config>
app/code/MyNamespace/MyModule/Observer/AddCustomLayoutUpdateHandle.php
<?php

namespace MyNamespace\MyModule\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Layout as Layout;
use Magento\Framework\View\Layout\ProcessorInterface as LayoutProcessor;

class AddCustomLayoutUpdateHandle implements ObserverInterface
{

    const LAYOUT_HANDLE_NAME = 'my_custom_layout';

    /**
     * @var Registry
     */
    private $registry;

    /**
     * @param Registry $registry
     */
    public function __construct(
        Registry $registry
    ) {
        $this->registry = $registry;
    }

    /**
     * @param Observer $observer
     *
     * @return void
     */
    public function execute(Observer $observer)
    {
        /** @var Event $event */
        $event = $observer->getEvent();
        $actionName = $event->getData('full_action_name');
        /** @var \Magento\Catalog\Model\Category $category * */
        $category = $this->registry->registry('current_category');

        if ($category && $actionName === 'catalog_category_view') {
            if ($category->getName() == 'shop') {
                /** @var Layout $layout */
                $layout = $event->getData('layout');

                /** @var LayoutProcessor $layoutUpdate */
                $layoutUpdate = $layout->getUpdate();
                $layoutUpdate->addHandle(self::LAYOUT_HANDLE_NAME);
            }
        }
    }
}
app/code/MyNamespace/MyModule/view/frontend/layout/my_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" layout="1column">
    <body>
        <attribute name="class" value="my-shop-category" />
        <referenceContainer name="div.sidebar.main" remove="true"/>
    </body>
</page>

Name (required)Email (required)Website

Leave a Reply