Magento – better way to add layout updates to a category rather than using the “Custom Layout Updates” field

categorylayoutmagento-1.7page-layoutstemplate

Here's the issue in a nutshell; I have a module adding custom templates that can be used for CMS Pages or Categories. The layout I'm using has updates in local.xml referencing the layout_handle declared in the module's config.xml.

If I apply the template to a page, the updates in local.xml work fine. If I apply that same template to a category, the layout updates do NOT work and are ignored.

Here's some of the code so you can get an idea of what I'm talking about:

Module config.xml adding the layouts

<global>
    <page>
      <layouts>
        <tf_homepage translate="label">
          <label>Homepage</label>
          <template>page/homepage.phtml</template>
          <layout_handle>tf_homepage</layout_handle>
        </tf_homepage>
        <tf_categorytoplevel translate="label">
            <label>Category: Top Level</label>
            <template>page/2columns-left.phtml</template>
            <layout_handle>tf_categorytoplevel</layout_handle>
        </tf_categorytoplevel>
      </layouts>
    </page>
</global>

This is the snippet from local.xml doing the updates

<tf_categorytoplevel>
    <reference name="root">
        <action method="setTemplate">
            <template>page/2columns-left.phtml</template>
        </action>
        <action method="addBodyClass"><className>catalog-category-layered</className></action>
    </reference>
    <reference name="product_list">
        <action method="setColumnCount">
            <count>3</count>
        </action>
    </reference>
    <reference name="product_list_toolbar">
        <action method="setDefaultGridPerPage"><limit>12</limit></action>
    </reference>
</tf_categorytoplevel>

As a simple test, when the layout is applied to a CMS page, the body class is added properly and the layout changes. When applied to a Category page, the body class is not added and the layout does not change.

If I add the local.xml snippet to the Custom Layout Updates field on the category page, the Category page shows up the way I expect — there has to be a better way to do it, though.

I've even tried adding <update handle="tf_categorytoplevel" /> to the Custom Updates Field (also didn't work).

This has been driving me crazy — Do any of you know a better way to have a custom layout work properly with minimal interaction by the user? I want them to be able to choose the layout and just be done with it.

Best Answer

I'm not sure, wether I understand your question correctly.

When a category is loaded, there is a update-handle added: CATEGORY_<id>, e.g. CATEGORY_4. With this handle you can add specific layout updates to the local.xml if you know the id.