gil--
4/23/2017 - 3:16 AM

Magento 2 : Add Body Class using an observer

Magento 2 : Add Body Class using an observer

<?xml version="1.0"?><!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <attribute name="class" value="my_custom_class"/>
    </body>
</page>
<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<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_load_before" instance="MyVendor\MyModule\Observer\LayoutLoadBeforeObserver" />
    </event>
</config>
<?php
/**
 * @license http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 * @author Phuong LE <phuong.le@agence-soon.fr> <@>
 * @copyright Copyright (c) 2017 Agence Soon (http://www.agence-soon.fr)
 */

namespace MyVendor\MyModule\Observer;


use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;


class LayoutLoadBeforeObserver implements ObserverInterface
{
    /**
     * @var CustomerSession
     */
    private $customerSession;

    /**
     * LayoutLoadBeforeObserver constructor.
     * @param CustomerSession $customerSession
     */
    public function __construct(
        CustomerSession $customerSession
    ) {
        $this->customerSession = $customerSession;
    }

    /**
     * @param Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        /** @var \Magento\Framework\View\Layout $layout */
        $layout = $observer->getEvent()->getData('layout');
      /** Set Your logic here */
        if ($this->customerSession->getData('my_data')) {
            $layout->getUpdate()->addHandle('my_custom_handle');
        }
    }
}