How to Modify Magento Rendered Page Before Display

cmsfrontendmoduleproduct

I am trying to modify the rendered page content before it's displayed to the user. I would like to do this in my custom module.

So far, I have tried hooking into the cms_page_render event but:

  • it does not work for product pages
  • it doesn't hold the final HTML; it still has Magento templating tags

How do I go about modifying the rendered page content right before it's displayed to the user?

Best Answer

If you need to change the content of a page using in observer means you need to do something with layout of the page. There are lot of events available to alter the layout of magento. To select the right one is simply depends upon where you need to change the output and conditions.

If you classify Magento events, we can see that, there are some general events, specific events and there are some dynamic events too. General events means events that get called in every page load request. Specific events means events that get called during some special occasions, means during some specific page loads. Dynamic events are kind of dynamic events. Difference is their names are dynamic, it will change depend upon which module processing.

In this case, you just want to change the content part. But there are many events that allow us to change the layout of the requested page. You can use these events controller_action_layout_load_before or controller_action_layout_load_after to change the layout structure directly. These events are specific for layout alterations. Now if you want to change the blocks, add blocks, change the template that is using by a block etc, you can use controller_action_layout_generate_blocks_before or controller_action_layout_generate_blocks_after events. Now ..

If you need to directly alter the html content of a page, you can use core_block_abstract_to_html_after. Here the html content of the page is passing through transport object. So if you observe on this event, then in your observer you can get the html content as like this

public function someFunction($observer)
{
    $block = $observer->getBlock();

    //if you trying to chang product view page content.
    if ($block instanceof Mage_Catalog_Block_Product_View) {
        $transport = $observer->getTransport();
        $html = $transport->getHtml();
        $html .= 'We need to append something here';
        $transport->setHtml($html);
    }
}
Related Topic