Magento 2 custom layout add body class
Page Layout XML
As far as I'm aware this isn't possible out of the box via page layout XML, the existing implementation is done via PHP (checkout the addDefaultBodyClasses()
function here);
/**
* Add default body classes for current page layout
*
* @return $this
*/
protected function addDefaultBodyClasses()
{
$this->pageConfig->addBodyClass($this->request->getFullActionName('-'));
$pageLayout = $this->getPageLayout();
if ($pageLayout) {
$this->pageConfig->addBodyClass('page-layout-' . $pageLayout);
}
return $this;
}
Layout XML
Just in case anyone ends up on this question for standard layout XML it can be done this way:
Add the following attribute inside the <body>
tags.
<body>
<attribute name="class" value="your-class"/>
</body>
If this doesn't work you may need to clear your caches?
The only solution i've found is to add a class to the root container. This element will be displayed immediately after the body tag.
I've used this code:
<referenceContainer name="root" htmlTag="div" htmlClass="custom-class">
</referenceContainer>
For me worked in the Layout Update XML for CMS pages and categories.
Unfortunately is the only solution iv'e found similar to the old "addBodyClass".
You can do this using a Observer:
=> Create the file :
app/code/Myvendor/Mymodule/etc/frontend/event.xml
with the following content:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<event name="layout_generate_blocks_after">
<observer name="samgranger_storecodebodyclass" instance="Myvendor\Mymodule\Observer\AddBodyClass" shared="false" />
</event>
</config>
=> Create the file :
app/code/Myvendor/Mymodule/Observer/AddBodyClass.php
with the following content:
<?php
namespace Myvendor\Mymodule\Observer;
use Magento\Framework\View\Page\Config;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer as EventObserver;
class AddBodyClass implements ObserverInterface
{
public function __construct(
Config $config
){
$this->config = $config;
}
public function execute(EventObserver $observer){
$name = $observer->getFullActionName();
$layout = $observer->getLayout();
if($name == "amblog_index_category") {
$this->config->addBodyClass("events-page");
}
}
}