Re-using Handles in Magento Layout XML

Magento layout xml files can be really confusing. Here is a post to make them even more confusing, but really useful.
I won’t cover how to create a layout xml file here, I’ll cover that in a different post. I’m going to show you how to re-use the handles in your module.
Let’s say your module has the following layout xml. It’s just a one page module so it is simple:

<?xml version="1.0"?>
<layout version="1.0.0">
    <mymodule_default>
        <reference name="head">
            <action method="addItem">
                <type>skin_css</type>
                <name>css/mymodule.css</name>
            </action>
            <action method="addItem">
                <type>skin_js</type>
                <name>src/js/mymodule.js</name>
            </action>
        </reference>
    </mymodule_default>
    <mymodule_index_index>
        <update handle="mymodule_default" />
        <reference name="content">
            <block type="core/template" name="mymodule.main" template="mymodule/index.phtml">
                <block type="core/template" name="mymodule.child1" template="mymodule/index/childblock1.phtml"/>
                <block type="core/template" name="mymodule.child2" template="mymodule/index/childblock2.phtml"/>
            </block>
        </reference>
    </q_index_index>
</layout>

Take a look at the <update handle="mymodule_default" /> line in the <mymodule_index_index> section.What that is doing is copying everything in the <mymodule_default> section into that section.
This is really useful. You can use this same method to copy basically any block into another block.
For example, lets say you want to create a new section that includes the same templates that are in your <mymodule_index_index> section. You would add this to your xml:

<mymodule_newblock_index>
    <update handle="mymodule_index_index" />
</mymodule_newblock_index>

That section would include everything that is in the <mymodule_index_index> section.
Have fun re-using handles!

Leave a Reply