Magento: More Flexibility For Your Layout Updates

I’ve been working on a project with a lot of requirements for certain templates or javascript to be added based on a lot of different conditionals and situations that the standard layout xml files do not really allow for. Fortunately, there are events and methods that you can use to add in xml on the fly without the need for layout xml files, allowing the ability to add in logic as to what and if something should be added or not.

First thing you are going to want to do is create an event observer to observe the ‘controller_action_layout_generate_xml_before’ event. That event will provide you with the layout object. By accessing the Update object from the layout, we can easily add in our own update:

$layout = $observer->getLayout();
    <reference name="content">
        <block type="module/block" name="" template="your/template.phtml" />

If you wanted that block only to be added if the customer is not logged in, you could wrap the code in a conditional. You could get quite creative with this in implementing all sorts of cool functionality as we have done on our project. I hope this provides the tool to get you started!

This entry was posted in Magento. Bookmark the permalink.

2 Responses to Magento: More Flexibility For Your Layout Updates

  1. jasontrinh says:

    Your blog is so useful! Thank so much!

  2. Yaroslav says:

    Great blog you have indeed. This post in particular seems to be what I’m looking for right now. I’m trying to dinamically add two blocks (also dinamically generated) on the product view page on a theme we bought recently. I’m guessing this approach will be helpful. What’s your opinion based on your experience?