Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Magento 2 : Add Body Class using an observer
<?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(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');
}
}
}
<?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>
@dfelton

This comment has been minimized.

Copy link

commented Aug 3, 2017

FYI this use statement is unecessarysince you're utilizing the full class name later on.

Thanks for the quick reference 👍

@0-Sony

This comment has been minimized.

Copy link
Owner Author

commented Jan 18, 2018

Hey thanks for your comment, you right ! I m going to modify the file :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.