Skip to content

Instantly share code, notes, and snippets.

@0-Sony
Last active May 14, 2021 14:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save 0-Sony/57de53857abb7245c9d4a902d8c57fe3 to your computer and use it in GitHub Desktop.
Save 0-Sony/57de53857abb7245c9d4a902d8c57fe3 to your computer and use it in GitHub Desktop.
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
Copy link

dfelton 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
Copy link
Author

0-Sony 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