pls help me! How to Add a class or id to html or body when changing the language magento 2


Add the store code class at body using the observer

1.first you have to create a custom module

2.you have to create the observer for layout_load_before at Namespace/Modulename/etc/frontend/events.xml and write down the below code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <event name="layout_load_before">
        <observer name="cutom_bodystoreclass" instance="Namespace\Modulename\Plugin\BodyStoreClass" shared="false" />

2.Now create the folder Plugin and create the file BodyStoreClass.php in your Modulenae folder and write down the below code

namespace VoolaTech\StoreClass\Plugin;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\View\Page\Config;
use Magento\Store\Model\StoreManagerInterface;
class BodyStoreClas implements ObserverInterface
    protected $config;
    protected $storeManager;
    public function __construct(
        Config $config,
        StoreManagerInterface $storeManager
        $this->config = $config;
        $this->storeManager = $storeManager;
    public function execute(Observer $observer){
        $store = $this->storeManager->getStore();
        $storeCode = $store->getCode();
        $websiteCode = $store->getWebsite()->getCode();

3.Now remove the folder genarated and var using command line

rm rf generated/ var
| improve this answer | |

If you look at source code

<!doctype html>
<html lang="en">
[... stuff ...]

The source code you are looking for is located in vendor/magento/module-theme/view/base/templates/root.phtml.

To change this behavior copy the above file to your current theme directory.


Then do something like this

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$dynamicVariable     = $storeManager->getStore()->getName();
<html <?= $htmlAttributes ?> class="<?= $dynamicVariable; ?>">

It's a simple example but that should be enough to get you started.

And although I've used the object manager you could do a neater job with helper or ViewModel if using 2.3.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.