Creating Our Own Layout Handles
In terms of reusability, we can compare layout handles in Magento with user defined functions in normal code. A user defined function may contain a snippet of code to be used in many places, so that we just need to call the function where needed instead of repeating the same code everywhere.
Layout handles can be used in a similar way. In a page, there may be some specific layout changes which are repeated for other pages, for example, adding a block in the right sidebar, removing a block from the left sidebar, defining the root template to use 3 columns, 1 column, 2 columns with left sidebar, etc… We can create a layout handle which defines these repeating changes in one place and then we can just specify the layout update handle for any other page where we need this specific layout change.
Let’s take a simple example. Let’s say that we need the following layout changes in more than one page:
Remove the cart sidebar block from the right sidebar
Insert a CMS block with identifier foo in the left sidebar
Use the 3 column layout for the page
We have to define a unique name for the handle that doesn’t conflict with the name any existing layout handles. In our example, we will give the layout handle the name foo_bar_handle.
Here is the layout XML code to define this handle:
<foo_bar_handle>
<reference name="right">
<remove name="cart_sidebar" />
</reference>
<reference name="left">
<block type="cms/block" name="foo">
<action method="setBlockId"><identifier>foo</identifier></action>
</block>
</reference>
<reference name="root">
<action method="setTemplate"><template>page/3columns.phtml</template></action>
</reference>
</foo_bar_handle>
Now, let’s say, we need the above changes on all the product pages. So, we can call our layout handle on the product page like this:
<catalog_product_view>
<update handle="foo_bar_handle" />
</catalog_product_view>
This will update the product page with the layout changes specified in our custom layout update handle.
To keep all our layout updates in one central place, we recommend placing them in the local.xml file.