TutorialIntroducing The Magento Layout

Advertisement

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

Third-Party Tools Google Analytics, Reinvigorate and CrazyEgg1

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 Module2.

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?”

Feel free to view or download the source code3 (Github).

Try It Yourself

Now that we are all experts on the Magento layout, here are some very simple examples which follow the very same pattern, but demonstrate how easy it is to integrate third party software with Magento.

Since all of the information you need is detailed in the above article, I will provide some pointers on how you should approach each integration.

Google Analytics

Magento actually ships with Google Analytics, so it is in fact as simple as entering your tracking code in the admin panel; however, this does not make it any less useful as a try-it-yourself example.

The first step is to visit the Google website to retrieve the snippet of code that you need to include on your website. You will notice the only dynamic element of the standard tracking code is the account number (e.g. UA-12345678-90), so for the purpose of this example I would suggest making this number the dynamic content to be retrieved from the block. In a future article, we will cover the topic of making this kind of content admin panel configurable, so abstracting it to the block for now makes good sense should you wish to revisit this example.

Now on to creating your module. I would suggest keeping the same namespace for all of these examples, “SmashingMagazine,” and a fitting module name would be “GoogleAnalytics” in this case. You will need all of the elements of the main article above, so make your way through the article once more, adjusting as required. Since you want your code to appear on every page, you should now know the best layout handle to choose.

If you encounter any problems, check and double check that you have followed the main article exactly, as most beginner issues with Magento are typos and syntax-related mistakes.

Reinvigorate, CrazyEgg and Everything Else…

You should now see a pattern emerging! You can simply follow exactly the same steps again to integrate other popular third-party software with your Magento website, all without modifying a single core Magento file or having to copy and paste content directly into the admin panel, where somebody could accidentally delete it one day.

I welcome any questions and would love to hear any feedback in the comments area below.

(cp)

Footnotes

  1. 1 http://www.smashingmagazine.com/wp-content/uploads/2012/11/Introducing-The-Magento-Layout-no-frame1.png
  2. 2 http://www.smashingmagazine.com/2012/03/01/basics-creating-magento-module/
  3. 3 https://github.com/josephmcdermott/SmashingMagazine-MagentoLayout

↑ Back to topShare on Twitter

Advertising
  1. 1

    Oh, this article is perfect! Thank you so much.

    -3
  2. 2

    Thats why I use Prestashop and not magento its way too complex.

    -8
  3. 3

    Indeed Magento seems to be a very complex system to work/code with… But the article is very interesting… Thanks!

    2
  4. 4

    A good walkthrough, one which explains several oft-misunderstood points quite well. I’d like to note a couple other details as well:

    It is imperative to not hardcode protocols in templates, especially in templates which are rendered via pervasive layout update handles (e.g. before_body_end). These are rendered as written and will throw mixed content warning when the site is in a secure area such as the checkout.

    The other (very minor) note: specifying a version for this module is unnecessary as it does not have a corresponding setup resource declared. A complete nit-pick of a detail, but one that seems in keeping with the other very good points.

    9
  5. 5

    Thanks for dissecting Magento and writing this concise article. It is very helpful. Though, I have found Magento to be extremely difficult to work with, and try to avoid it at all cost.

    3
  6. 6

    So it is complex. Yes.
    Having a steep learningcurve, as I experienced myself, but:
    Understanding the logic of the Magento layout, gives you flexibility and makes you build reusable blocks of code.

    I especially like the way you can override the ‘local.xml’ on a category or even product level: enabling custom layouts very easy from the backend as well!

    8
  7. 7

    Excellent point re: protocol hard coding Ben. Magento provides the functionality to determine whether a page is HTTPS or not, so the addition of a method like getIsSecure() in the Block is recommended, to return the result of: Mage::app()->getStore()->isCurrentlySecure();

    Alternatively, the Block method could be getProtocol(), returning the result of Mage::app()->getStore()->isCurrentlySecure() ? ‘https’ : ‘http';

    And of course you have the brute force option to hard code the protocol to https :)

    As for the version number, again a good point however we sometimes include this number to identify the version of a module on particular clients environments, which can occasionally help debug issues or identify required upgrades. If a setup resource is later required, we would create the install script at version 0.0.3 or whatever the module was up to.

    Thanks for your feedback, Ben.

    2
  8. 8

    Code is so complicated as if it was written for extremely expensive product a-la SAP ERP where employers gladly pay for 6-12 months of internship for new staff to learn the system.

    1
  9. 9

    Thats why I use Prestashop and not magento its way too complex.
    Here my website in BRAZIL: http://www.blogdobinhuh.com/

    -4
  10. 10

    Magento is great once you get to know it. I’ve been using Magento since 2008 and it is indeed a very complex system. But I like its design flexibility and wouldn’t switch to another e-commerce platform.
    I’m using it on my t-shirt site – http://www.createur.ro

    2
  11. 11

    Great tutorial. It helps me a lot. I’m looking forward for your next tutorial about “Content configurable from admin panel “. I mean “Module to integrate the dynamic content from admin panel” . Thanks a lots.

    2
  12. 12

    Great tutorial for every magento users. Magento is a bit complicated but with powerful function it brings to user, it deserves to be the best ecommerce platform.
    If you guys are looking for free magento extensions or many magento tutorials, you can take a look at our website http://www.magestore.com/magento-extensions.html

    1
  13. 13

    You can also just use “//”. For example: This <img src=”//www.site.com/image.png” /> will (should) be recognized by clients as matching the current scheme (i.e. http or https).

    3
  14. 14

    super article. loved it

    0
  15. 15

    Thanks for this great magento tutorial. Everyone may also refer this tutorial about Magento Layout Files Structure
    http://tutorialmagento.com/magento-video-tutorials-31-theming-magento-7-layout-files-structure

    0
  16. 16

    I think this tutorial help me a lot . However while I created config.xml and xml file which is added in app/etc/module, I couldn’t find my file in system/configuration. That is because of a single error. you do not need to use the xml declaration .Just remove that line and then it will works fine. Hope it will help to solve the issue. Thanks

    0
  17. 17

    Thanks for this great magento tutorial. Everyone may also refer this tutorial about Magento Layout Files Structure.
    You can see my blog about magento product label at http://magentoproductlabel.wordpress.com/

    0
  18. 18

    Jesus G-Force Harris Jr

    December 23, 2013 1:53 pm

    This article deserves my email. Clearest instructions on how to nail the magento layout by a whale’s torso. Love the format of the tutorials – so easy to follow in comparison with a lot of congested, messy pieces out there – believe me – I’ve trawled!

    Power to you Joseph<

    0
  19. 19

    This is Shyam i copied my theme from main domain to sub domain using cpanel but the out put is different from original. Can u help me where did the mistake

    0
  20. 20

    Hi,

    Great article. Helped me alot. Just one question:

    How can I add the custom block in one specific place for instance? I want it before the content but the ways I tried didn’t work.

    0
  21. 21

    Arvind Bhardwaj

    May 12, 2014 8:18 am

    Nice article.
    Here is a short intro of How to integrate Angular js with Magento: http://www.webspeaks.in/2014/03/integrating-angular-js-with-magento.html

    0
  22. 22

    Thank you for a great post. It is very useful for any Magento users, even developers like us. We are giving lots of premium & free extensions at http://www.magebuzz.com/

    -2

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top