Magento – Adjust the HTML Body Class of your pages via Layout XML
When it comes to Magento, I’m mostly a frontend developer. I’ve written some modules – some of which I’m working on sharing with you, public – but for the most part I stick with it’s core functionalities and just edit the template HTML & CSS files.
As such, I found myself wondering how I could add a new class name to the body tag in the HTML. I at first checked the skeleton template files in the page/ directory of the template; and it just referenced a function. After a little hunting, I found out the correct way to add a new class in Magento – via the layout files.
If you don’t get the layout file concept of Magento, you really ought to look into it. I’m not here to enlighten you about that.
Anyway – you can add new body classes on a per module basis. So let’s say we want to give all the “my account” pages a body class of… account-control. This can be very useful to add a generic style across the board to each account page that is separate from the styling of the rest of the site.
You’d need to find the appropriate module block (I believe it is customer_account) and paste the following code in
-
-
<reference name="root">
-
<action method="addBodyClass"><classname>account-control</classname></action>
-
</reference>
-
That’s it! Make sure you refresh your cache if necessary, and refresh the account pages after logging into a user account. Check the source – an additional body class of “account-control” has been added!
I wasn’t as specific as I could have been about things in this article; let me know if you have any troubles and I’ll update as necessary for all you n00bs.
Cheers
RSS feed for comments on this post.
Do you know if there is a way to add a body class to specific pages, for example the about us page.
I am actually trying to do something that outside of magento is very easy, that is to assign an active state to a menu button when selected.
I actually thought that styling it via the body tag might be one way of doing it.
Thanks
Lee
Check the source code for the about us page – pages like htat should already be given a specific body class by Magento. It may have a class name that is a little long, ugly, and uninformative – but it’ll do for a quick CSS rule on an active state.
I wrote those post mainly for those trying to make a better class name or add onto the ones Magento builds.