Magento 1.9 – Add Multiple Classes to Body Tag

magento-1.9

I am trying to add multiple classes to body tag in magento using addbodyclass method in my local.xml file.

Code in my local.xml file

<reference name="root">
     <action method="addBodyClass">
        <className helper="mymodule/addbodyclass/addClasses" />
     </action>
</reference>

Code in my Helper class in a custom module:

class Mycompany_Mymodule_Helper_Addbodyclass extends Mage_Core_Helper_Abstract
{
    public function addClasses() {
        return "classname1 classname2 classname3";
     }
}

This adds classes in one string like this:

classname1-classname2-classname3

in the body tag.

Instead of spaces it adds dash(-). I know this is default behavior of magento. But is there a way to actually add spaces and not dash(-).

Thank You

Best Answer

So basically the addBodyClass method replaces some characters with - on the fly using regular expression:

public function addBodyClass($className)
{
    $className = preg_replace('#[^a-z0-9]+#', '-', strtolower($className));
    $this->setBodyClass($this->getBodyClass() . ' ' . $className);
    return $this;
}

As you can see, when this method is called the original body classes are updated and the extra body class is added with a space between the original classes. So in order to add several classes I suggest you do the following in your xml file:

<action method="addBodyClass">
     <className>classname1</className>
</action>
<action method="addBodyClass">
     <className>classname2</className>
</action>
<action method="addBodyClass">
     <className>classname3</className>
</action>

If you really want to be able to add several classes to the body using that method, then you will need to create a custom module that extends that method:

config.xml

<?xml version="1.0"?>

<config>

    <modules>
        <DigitalPianism_Multiplebodyclass>
            <version>0.0.1</version>
        </DigitalPianism_Multiplebodyclass>
    </modules>
    <global>
         <blocks>
              <page>
                   <rewrite>
                        <html>DigitalPianism_Multiplebodyclass_Block_Page_Html</html>
                   </rewrite>
              </page>
         </blocks>
    </global>

</config>

Block/Page/Html.php

<?php

class DigitalPianism_Multiplebodyclass_Block_Page_Html extends Mage_Page_Block_Html
{
    public function addBodyClass($classNames)
    {
        if (is_array($classNames))
        {
            foreach($classNames as $className)
            {
                parent::addBodyClass($className);
            }
        }
        else parent::addBodyClass($classNames);
        return $this;
    }
}

Then in your custom helper you will be able to do:

public function addClasses() {
        return array('classname1','classname2','classname3');
     }
Related Topic