5 min read

How to Conditionally remove Magento header/footer?

How to Conditionally remove Magento header/footer?

Last modified

In some cases there is a need to remove Magento header or footer from pages, for example you are creating some custom landing page and you don’t want to put header or footer or want to remove both from that page, this tutorial will help you achieving it.

Need help? You can Email me or Skype chat

Scenario:

You have a module page that can be accessed like

www.yoursite.com/module/controller/action/id/10

And you want to unset header and footer based on id parameter, for example you don’t want header and footer appear when id is 10.

Wrong way to go:


$page = (int) Mage::app()->getRequest()->getParam('id');
if($page == '12')
{
    $this->getLayout()->unsetBlock('header');
    $this->getLayout()->unsetBlock('footer');
}

But you can’t unset header footer like above code.

 

Solution creating custom layout handle:

Fortunately, Magento’s layout engine is flexible enough to provide a way to define our own layout handles and call them explicitly through custom extensions. It’s easy to update unique page layouts by utilizing Magento’s built in ability to insert additional layout handles using an Observer. Let’s see how to create our own layout handles.

  1. Create a new observer Observer.php in models directory of your module to assign a new handle as shown below
    
    Class Namespace_Modulename_Model_Observer extends Mage_Core_Model_Abstract
    {
    
        public function addAttributeSetHandle(Varien_Event_Observer $observer)
        {
            $page = (int) Mage::app()->getRequest()->getParam('id');
            $handle = sprintf('modulename_controller_action_id_%s', $page);
            $update = $observer->getEvent()->getLayout()->getUpdate();
            $update->addHandle($handle);
        }
    }
    
  2. Enable the new observer in module’s config.xml
    
    <frontend>
        <events>
            <controller_action_layout_load_before>
                <observers>
                    <attributesethandle>
                        <class>Namespace_Modulename_Model_Observer</class>
                        <method>addAttributeSetHandle</method>
                    </attributesethandle>
                </observers>
            </controller_action_layout_load_before>
        </events>
    </frontend>
    

    The event controller_action_layout_load_before will attempt to run addCustomHandles function in the Oberserver every time the controller action is called.

  3. And lastly change the layout for the handle modulename_controller_action_id_12 in modules layout xml.
    
    <modulename_controller_action_id_12>
        <remove name="header"/>
        <remove name="footer"/>
        <reference name="root">
            <action method="setTemplate">
                <template>page/1column.phtml</template>
            </action>
        </reference>
    </modulename_controller_action_id_12>