2

I have a custom category attribute that i want to add to the body class. As far as I could find out what people do is

  1. Override the CategoryController and add something like $root->addBodyClass($category->getMyAttribute()); But I don't want to override core classes...

  2. In the admin panel they add something like <reference name=”root”><action method=”addBodyClass”><className>caravan-motorhome-lighting</className></action></reference> to each and every category not using the attribute itself but adding the class directly. As I already have an attribute, I surely don't want do clone it and add the class this way.

So what my favourite solution would be is some layout update I can add to the local.xml that says

<reference name=”root”>
    <action method=”addBodyClass”>
        <className>
            get value of my custom attribute here dynamically
        </className>
    </action>
</reference>

Does anyone have an idea how this could work or another idea that I didn't even think of?

Ria Weyprecht
  • 1,267
  • 9
  • 18

1 Answers1

6

You can use a really cool feature of Magento layout XML to achieve this. You'll need a module to achieve it. Either create a module specifically for this or use a theme module if you have one — this is up to you to decide what you think is best.

I'll show you an example where I'll add a class containing the ID of the category to the body tag:

In my layout XML, I'm going to add via the catalog_category_default handle. This way, I can use Mage::registry('current_category') later to retrieve the current category. So, in your layout XML do something similar to this:

<catalog_category_default>
    <reference name="root">
        <action method="addBodyClass">
            <className helper="mymodule/my_helper/getCategoryClass" />
        </action>
    </reference>
</catalog_category_default>

This attribute is the important part: helper="mymodule/my_helper/getCategoryClass". This is equivalent to calling Mage::helper('mymodule/my_helper')->getCategoryClass(); in code.

Whatever is returned from that function will be used as the value for the <className> node. You may want to use a different helper that you deem more appropriate, this is up to you to decide.

Carrying on the with the example, here's the function:

public function getCategoryClass() {
    return 'category-id-' . Mage::registry('current_category')->getId();
}

You'll want to change the code so that it retrieves the value of your attribute. e.g getMyAttribute() on the category returned by Mage::registry('current_category').

Also, you'll need to ensure that the return is something that is suitable as a CSS class. In this example we don't need to do anything as the ID will always be just number which will be appended to category-id-. If the value of your attribute is not always going to be safe you might want to consider using something like this

It works!

Community
  • 1
  • 1
Josh Davenport
  • 5,308
  • 2
  • 25
  • 40