Thursday, April 18, 2013

Introducing The Magento Layout

Magento Layout
In this tutorial, we introduce the Magento layout by creating a simple module that will add some custom HTML content to the bottom of every customer-facing page, in a non-intrusive manner. In other words, we will do so without actually modifying any Magento templates or core files. This kind of functionality is a common requirement for many things such as affiliate referral programs, customer tracking analytics, adding custom JavaScript functionality, etc.

We will be covering a number of interesting topics, including:

  • Magento layout handles
  • Layout XML files
  • Blocks and templates
  • An alternative to Widgets

Once you have understood this article, you will have all the information you need to integrate popular third-party tools such as:

  • Google Analytics
  • Reinvigorate
  • CrazyEgg

Before We Start

This tutorial assumes that you are already familiar with creating your own Magento module, so if you haven't already done so, I recommend reading our previous article on Creating a Magento Module.

Okay, lets get started. The file structure of our new module should look like this:

app
  - code
      - local
          - SmashingMagazine
              - Layout
                  - etc
                      - config.xml

  - etc
      - modules
          - SmashingMagazine_Layout.xml

We can leave config.xml empty for now, as we will be populating it later on in the tutorial, but we can already complete the content of SmashingMagazine_Layout.xml, with:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <SmashingMagazine_Layout>
            <active>true</active>
            <codePool>local</codePool>
        </SmashingMagazine_Layout>
    </modules>
</config>

Introducing The Magento Layout

The content that is displayed on each Magento page is largely determined by the layout XML files, which can be found in app/design/frontend/base/default/layout. In these XML files, you will see a number of snippets of XML enclosed in layout handle parent nodes, which are used to determine the type of page being displayed. For example, the handle catalog_product_view is used to add content to the product detail page and checkout_cart_index the basket page.

Child nodes are then created inside these layout handles to determine which content should appear on any particular page. These child nodes are called blocks, which may in turn contain child blocks of their own. For example, in a layout XML file for the product page (see app/design/frontend/base/default/layout/catalog.xml), under the catalog_product_view layout handle, we might find a block for displaying the product wrapper template. Then as children of that block, we would find a block for the product image template, a block for displaying the price template and another for displaying the add to basket template.

Each of these blocks has a template associated with it. In Model–View–Controller (MVC) terms, the block acts as a mini controller and the template acts as the view. All of the logic for displaying dynamic content is found in the block, which is requested by the template and displayed in HTML form.

The Magento layout is quite a complex, yet very powerful, beast and as a result we will only cover the parts that are relevant to this tutorial. There is a layout handle named default which is included on every page and since we want our module's HTML content to appear at the bottom of every page, this is the layout handle we will use.

Adding A New Layout File

We need to define a new layout file to contain our updates, so first we need to modify our module's config.xml to cater to layout updates:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <SmashingMagazine_Layout>
            <version>0.0.1</version>
        </SmashingMagazine_Layout>
    </modules>
    
    <!-- we are making changes to the frontend -->
    <frontend>
        
        <!-- we are making changes to the layout -->
        <layout>
            
            <!-- we are adding a new update file -->
            <updates>
                
                <!-- 
                    this child node name must be
                    unique throughout Magento
                -->
                <smashingmagazine_layout 
                         module="SmashingMagazine_Layout">
                    
                    <!-- the name of the layout file we are adding -->
                    <file>smashingmagazine_layout.xml</file>
                    
                </smashingmagazine_layout>
                
            </updates>
            
        </layout>
        
    </frontend>

</config>

Now let's create this layout XML file here:

app
  - design
      - frontend
          - base
              - default
                  - layout
                      - smashingmagazine_layout.xml

Now those of you who have a little Magento experience, or have read any more noteworthy Magento tutorials, may be gasping at the fact we are making changes in base/default since this is where Magento core files are located. However, we are not modifying any files here, we are creating new ones and furthermore we are prefixing our file name with "smashingmagazine", so there is very little chance of this conflicting with other modules or causing any issues with upgrading Magento in the future.

The content of our new layout file will be as follows:

<?xml version="1.0" encoding="UTF-8"?>

<!-- all layout files begin with this node -->
<layout>
    
    <!-- this is the layout handle we are interested in -->
    <default>
        
        <!-- this is the name of the block we want to add to -->
        <reference name="before_body_end">
            
            <!-- 
                here we define our new block and template 
                to be added to 'before_body_end' 
            -->
            <block type="core/template" 
                   name="smashingmagazine_layout_footer" 
                   template="smashingmagazine_layout/footer.phtml" />
            
        </reference>
        
    </default>
    
</layout>

Here we have referenced an existing block, before_body_end, in order to add our own block, smashingmagazine_layout_footer, as its child. before_body_end is the name of a block that has its content output just before the </body> tag of the page HTML. You can find the definition of this parent block by looking in app/design/frontend/base/default/layout/page.xml and the content of this block is output in the .phtml templates within app/design/frontend/base/default/template/page.

By using reference, we are able to add content to existing blocks without needing to modify core Magento files. For example, we could achieve the same result as the above snippet by modifying app/design/frontend/base/default/layout/page.xml directly and adding our block code, but this is not good practice:

<default translate="label" module="page">
    <label>All Pages</label>
    <block type="page/html" name="root" output="toHtml" 
           template="page/3columns.phtml">

        ...

        <block type="core/text_list" name="before_body_end" 
               as="before_body_end" translate="label">
            
            <label>Page Bottom</label>
            
            <block type="core/template" 
                   name="smashingmagazine_layout_footer"
                   template="smashingmagazine_layout/footer.phtml" />
            
        </block>

        ...

    </block>
</default>

Adding A New Template File

We have now defined a new block, smashingmagazine_layout_footer and assigned the template smashingmagazine_layout/footer.phtml to contain our HTML content. Let's create that template file now:

app
  - design
      - frontend
          - base
              - default
                  - template
                      - smashingmagazine_layout
                          - footer.phtml

The content of footer.phtml can be whatever we like, but for this tutorial we will create a very simple template containing an image, functionality which is often required by affiliate tracking integrations:

<img 
    src="http://media.smashingmagazine.com/themes/smashingv4/images/logo.png?date=YYYY-MM-DD"
    width="459"
    height="120"
/>

Now it's time to take a look at the front end. Upon viewing any customer-facing Magento page, you should see an image displayed at the bottom and upon viewing the source of the page, you will see it has been included just before the <body/> tag.

Creating A New Custom Block

Now we want to tie in some simple logic to our template. The source of the image in our template includes a parameter date which currently contains a static value of YYYY-MM-DD. We want to be able to dynamically populate this parameter with the current date, for which we require some logic from our associated block.

At the moment, our template is associated with the default block type core/template, which only allows us some basic abstract block functionality. Therefore we must create our own custom block.

First let's modify the block type definition in smashingmagazine_layout.xml:

...
<block type="smashingmagazine_layout/footer" 
       name="smashingmagazine_layout_footer"
       template="smashingmagazine_layout/footer.phtml" />
...

Next let's update our module's config.xml to cater to custom blocks:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <SmashingMagazine_Layout>
            <version>0.0.1</version>
        </SmashingMagazine_Layout>
    </modules>
    <global>

        <!-- we are adding a new block definition -->
        <blocks>
            
            <!-- a unique short name for our block files -->
            <smashingmagazine_layout>
                
                <!-- the location of our module's blocks -->
                <class>SmashingMagazine_Layout_Block</class>

            </smashingmagazine_layout>

        </blocks>

    </global>
    <frontend>
        <layout>
            <updates>
                <smashingmagazine_layout
                         module="SmashingMagazine_Layout">
                    <file>smashingmagazine_layout.xml</file>
                </smashingmagazine_layout>
            </updates>
        </layout>
    </frontend>
</config>

Now let's create this custom block PHP file:

app
  - code
      - local
          - SmashingMagazine
              - Layout
                  - Block
                      - Footer.php

Finally, let's define our block class and add a simple method for retrieving the current date:

<?php
class SmashingMagazine_Layout_Block_Footer
    extends Mage_Core_Block_Template {
		public function getDate() {
			$date = date('Y-m-d');
			return urlencode($date);
		}
	}

Retrieving Dynamic Content From A Block

Inside a Magento template, PHP's $this keyword contains a reference to the associated block object, so we can call the method $this->getDate() directly from our template:

<img 
    src="http://media.smashingmagazine.com/themes/smashingv4/images/logo.png?date=<?php echo $this->getDate() ?>"
    width="459"
    height="120"
/>

Other Handles And Parent Blocks

Try experimenting by changing the layout handle from default to catalog_product_view or cms_index_index to see the HTML content appear only on the product page or the homepage respectively.

You can also try changing the location the content appears in our page's HTML by modifying the parent block from body_before_end to after_body_start or content.

Summary

This is a very simple example aimed at showing you the basics of how to make use of the Magento layout without needing to modify existing templates, which would potentially cause you problems when upgrading your Magento instance.

Using the techniques outlined in this tutorial, you could easily add something like Google Analytics tracking to every page, without needing to modify a single line in Magento's core templates. What's more, if you no longer wanted the custom HTML content on your website, you could simply disable the module and hey presto, it's gone!

The Magento layout is quite complex, and new developers might be tempted to simply "hack" the changes into the appropriate templates for the time being. However, the Magento layout is written in such a way that once we are familiar with it, we can unobtrusively add our custom content while not jeopardizing the ability to install community modules or to upgrade Magento without worrying, "will this work on my hacked-up Magento?".