Magento Under-the-Hood: Advanced Layout Techniques

Magento’s layout XML is really unique because it allows you to override the presentation elements of an eCommerce site in a variety of ways. At the simplest level, an XML layout file determines which blocks are rendered on the page. A block is a PHP object that encapsulates a portion of the page’s HTML output. In this article, I am going to cover the use of <action /> tags in XML layout files. If you need to take time to understand the basics of Magento blocks and layouts, start with the Designer’s Guide to Magento.

Calling PHP Functions

The <action /> tag allows you to invoke any public method of a block object. This is extremely useful, especially if you want to override specific block settings in a custom theme (eg. in your local.xml file). Using an action tag, you can set various data attributes of an existing block. Here is an example of how the action tag works:

<?xml version="1.0"?>
<layout version="0.1.0">
	<default>
		<reference name="head">
			<action method="addJs"><script>lib/PIE.js</script></action>
		</reference>
	</default>
</layout>

The above snippet will add the CSS3 PIE Javascript file in your header. On the PHP level, the XML code triggers the Mage_Page_Block_Html_Head::addJs() function with a string parameter of “lib/PIE.js”.

Array Parameters

So, what happens if you need to pass an array as a parameter? Until recently, I had no idea how to do this, but as it turns out, there is an undocumented feature of the action tag. See below:

<?xml version="1.0"?>
<layout version="0.1.0">
	<default>
		<reference name="content">
			<action method="setSomething" json="value"><value><![CDATA[
				{"associative" : "array"}
			]]></value></action>
			<action method="setSomethingElse" json="value"><value><![CDATA[
				["numeric", "array"]
			]]></value></action>
		</reference>
	</default>
</layout>

If you notice, the code above adds a json attribute to the action tag. This attribute is a space-separated list of child nodes that are to be run through a JSON decoder. To see how this works under the hood, checkout the source code (svn).

In the past, I have felt limited when using the action tag because methods could only take flat variables. However, given this “discovery”, I am confident that I can accomplish a great deal of customization without having to create custom blocks and modules. Hopefully this tactic will help you as well!

Further Reading

Magento 1.4 Development Cookbook Mastering Magento