Using layout update handles to change Magento page templates

I’d like to share a quick tip on updating Magento’s default page layouts using layout handles instead of the setTemplate method.

Most front-end developers who work with Magento themes will be familiar with the following code:

<catalog_product_view>
    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
    </reference>
</catalog_product_view>

It does pretty much what it says on the tin, changing the page template of the default product pages. I’ve seen this code repeated many times in local.xml files for many custom Magento themes.

While there is nothing wrong with this code, there is a more efficient update handle available to do the same job.

If you take a look in the page.xml file within app/design/frontend/base/default/layout/ and scroll to the bottom of the file, you will notice a number of page related update handles. As you can see, the layout handles already provide the necessary setTemplate action to change the page’s template for you:

<page_one_column translate="label">
    <label>All One-Column Layout Pages</label>
    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
        <action method="setIsHandle"><applied>1</applied></action>
        <action method="setLayoutCode"><name>one_column</name></action>
    </reference>
</page_one_column>

Applying these update handles within your themes local.xml file will eliminate the need to use the setTemplate action to update page layouts.

Using our previous product page example, we can now change the existing code to the following, achieving the same result.

<catalog_product_view>
    <update handle="page_one_column" />
</catalog_product_view>

Not only is this less code, it also ensures that we’re not needlessly repeating ourselves.