When creating a multi-page module in Magento 1, you will want to apply some custom XML layout changes to the pages from this module.
For example, let’s say every page in this module needs a javascript file loaded in the head of the document.
The Wrong Solution
You could add this to each page within the module in the layout XML, but that’s redundant and inefficient.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <mymodule_controller_index translate="label"> <reference name="head"> <action method="addJs"><script>my/custom/script.js</script></action> </reference> </mymodule_controller_index> <mymodule_controller_custompath translate="label"> <reference name="head"> <action method="addJs"><script>my/custom/script.js</script></action> </reference> </mymodule_controller_custompath> <mymodule_controller_anotherpath translate="label"> <reference name="head"> <action method="addJs"><script>my/custom/script.js</script></action> </reference> </mymodule_controller_anotherpath> |
The Correct Solution
The correct way to add a default XML layout declaration for your module is to create a default XML handle that applies the changes to all of the pages within this module.
1 2 3 4 5 | <mymodule_controller_default translate="label"> <reference name="head"> <action method="addJs"><script>my/custom/script.js</script></action> </reference> </mymodule_controller_default> |
This does nothing yet as Magento doesn’t know what to do with it just yet.
To make Magento aware of this XML layout handle, we need to extend one function in our controller.
1 2 3 4 | public function loadLayout($handles = null, $generateBlocks = true, $generateXml = true) { return parent::loadLayout( array('default','mymodule_controller_default '), $generateBlocks, $generateXml ); } |
And that’s it! That is the full solution. Now any page called through this controller will get the default XML layout applied to it. No extra work is required per page, etc. – just a one and done solution (as it should be).