Blog

Add Custom Layout Handles (e.g. Parent Categories)

If you ever need custom layout handles in your local.xml, it's fairly simple. In this example the observer method will make a new handle for for categories that have children or not, but you can just modify the method to make whatever handles you desire. (I realized after creating this there's already a handle for anchored categories with no subcategories, catalog_category_layered_nochildren)

First add this to your config.xml in yourcustommodule:

<config>
<frontend>
        <events>
            <controller_action_layout_load_before>
                <observers>
                    <yourcustomtheme_observer>
                        <class>yourcustomtheme/observer</class>
                        <method>addHandles</method>
                    </yourcustomtheme_observer>
                </observers>
            </controller_action_layout_load_before>
        </events>
</frontend>
</config>

Then add this method to your observer:

class YourPackage_YourCustomTheme_Model_Observer extends CLS_Core_Model_Abstract
{
    public function addHandles($observer) {
        $category = Mage::registry('current_category');
        if ($category instanceof Mage_Catalog_Model_Category) {
            $update = Mage::getSingleton('core/layout')->getUpdate();
            $fertilility = (count($category->getChildrenCategories()->getData())) ? 'parent' : 'nochildren';
            $update->addHandle('catalog_category_' . $fertilility);
        }
        return $this;
    }
}

Posted on June 1, 2011

Posted by Kevin Kirchner

Comments

Kevin's picture

I think $fertilility =

I think $fertilility = ($category->getChildrenCategories()->count()) ? 'parent' : 'nochildren'; might work. If so, it'd be better to do it that way probably.

Nice idea with the slug.

thaddeusmt's picture

Nice idea! One bug though (in

Nice idea! One bug though (in 1.5 at least): drop the ->getData() call. Just call it like this:


$fertilility = (count($category->getChildrenCategories())) ? 'parent' : 'nochildren';

An enhancement I made as well was to add another handle for specific categories:


if($slug = $category->getUrlKey()) {
$update->addHandle('catalog_category_' . $slug);
}

Add comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options