Magento 2, PHP

Magento 2: Add Store Code to Body Class

In some case we need to add a class to the body tag of your Magento stores, you’ll need to setup an event observer for the layout_render_before event.

See below for a more detailed example. In my example, I’m adding current store code and website code to the body.

Event: layout_render_before

File: etc/frontend/events.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_render_before">
     <observer instance="Uxmill\BodyStoreCode\Observer\Frontend\Layout\LoadBefore" name="uxmill_bodystorecode_observer_frontend_layout_loadbefore_layout_load_before"/>
  </event>
</config>

File: Observer/Frontend/Layout/LoadBefore.php


<?php
namespace Uxmill\BodyStoreCode\Observer\Frontend\Layout;

use Magento\Framework\Event\Observer;
use Magento\Framework\View\Page\Config;
use Magento\Store\Model\StoreManagerInterface;

/**
* Class LoadBefore
*
* @package Uxmill\BodyStoreCode\Observer\Frontend\Layout
*/
class LoadBefore implements \Magento\Framework\Event\ObserverInterface
{

   /**
    * @var Config
    */
   protected $config;
   /**
    * @var StoreManagerInterface
    */
   protected $storeManager;

   /**
    * LoadBefore constructor.
    *
    * @param Config                $config
    * @param StoreManagerInterface $storeManager
    */
   public function __construct(
       Config $config,
       StoreManagerInterface $storeManager
   ) {
       $this->config = $config;
       $this->storeManager = $storeManager;
   }

   /**
    * @param Observer $observer
    *
    * @throws \Magento\Framework\Exception\NoSuchEntityException
    */
   public function execute(Observer $observer)
   {
       $store = $this->storeManager->getStore();
       $storeCode = $store->getCode();
       $websiteCode = $store->getWebsite()->getCode();
       $this->config->addBodyClass($storeCode);
       $this->config->addBodyClass($websiteCode);
   }
}

GitHub code: https://github.com/durgagupta/magento2-bodyclas

Tags :