Reputation: 381
I am trying to figure out how to add css class to body tag programmatically using Magento 2 framework
Upvotes: 3
Views: 12690
Reputation: 6003
I've created an observer to layout_load_before
as follows:
...
public function __construct(
\Magento\Framework\View\Page\Config $pageConfig
) {
$this->_pageConfig = $pageConfig;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$this->_pageConfig->addBodyClass('my-new-body-class');
}
Upvotes: 5
Reputation: 411
See the following example that I created, this plugin adds the store code to the body class: https://github.com/samgranger/StoreCodeBodyClass
Place the plugin in app/code/SamGranger and run the usual scripts to enable it (bin/magento module:enable SamGranger_StoreCodeBodyClass + bin/magento setup:di:compile).
Upvotes: 0
Reputation: 3040
You can add a class to the body from a block by overriding the _prepareLayout
method:
public function _prepareLayout(){
$this->pageConfig->addBodyClass('my-class');
return parent::_prepareLayout();
}
Upvotes: 6
Reputation: 2325
Use the following code in layout to add css class or id to the body tag programmatically
<body>
<attribute name="class" value="custom-body-class" />
<attribute name="id value="custom-html-id"/>
For example - open the file customer_account.xml in layout folder MagentoDir > vendor > magento > module-customer > view > frontend >layout
after open the customer_account.xml file you can see to add css class
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" label="Customer My Account (All Pages)" design_abstraction="custom">
<body>
<attribute name="class" value="account"/>
Upvotes: 2