Magento的2:如何CSS类添加到body标签编程
使用下面的代码布局添加CSS类或ID到身体的标签编程
<body>
<attribute name="class" value="custom-body-class" />
<attribute name="id value="custom-html-id"/>
例如 - 在布局文件夹打开文件customer_account.xml MagentoDir>供应商>的magento>模块顾客>视图>前端>布局
后打开customer_account.xml科幻乐你可以看到添加CSS类
<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"/>
您可以将类从块通过重写_prepareLayout
方法添加到身体:
public function _prepareLayout(){
$this->pageConfig->addBodyClass('my-class');
return parent::_prepareLayout();
}
见我创建了下面的例子,这个插件增加(bin/magento模块:启用SamGranger_StoreCodeBodyClass + bin/magento setup:di:compile)。将插件放入app/code/SamGranger并运行常用脚本以启用它(bin/magento module:enable SamGranger_StoreCodeBodyClass + bin/magento setup:di:compile)。
我创建了一个观察者layout_load_before
如下:
...
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');
}
要注意的正确事件是“layout_load_before”,而不是“load_layout_before”。 – AfBu
谢谢@AfBu。我只是修复它。 –
编程 - 用PHP代码的意思! – valir