0

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

0

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.

app/design/frontend/YOURVENDORNAME/YOURTHEME/Magento_Theme/templates/root.phtml

Then do something like this

<?php
$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.

0

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"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="cutom_bodystoreclass" instance="Namespace\Modulename\Plugin\BodyStoreClass" shared="false" />
    </event>
</config>

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

<?php
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();
        $this->config->addBodyClass($storeCode);
        $this->config->addBodyClass($websiteCode);
    }
}

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

rm rf generated/ var

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.