How to add body class before rendering the page in Magento 2?

Magento 2 add body class with pages like cms, category, product and checkout page.

You can set cutom body class for the page in Magento 2 using plugin by Magento\Framework\View\Result\Page class.

If you want to add your own class for the page in <body> tag of the page, You can use the below code snippet to add class. Check the Path to define plugin: Jesadiya\BodyClass\etc\frontend\di.xml

Plugin class,
Path: Jesadiya\BodyClass\Plugin\Result\Page.php

You can add body class based on the configuration layout from the admin panel, If you have set the layout type from the admin panel, you got the Page layout type from the $subject->getConfig()->getPageLayout().

You can set predefined layout type from the admin panel for the CMS page, Product page or Category page.

Output:
When you check the 1column page body class, new class will be appended to body tag.

You can set custom body class for any page with the Plugin with before Rende Result method.

Leave a Reply