2

I am trying to use a custom event observer to observe the controller_action_postdispatch event and modify the response body directly by replacing opening head tag with + my custom block content. It is important that I make sure that it is an actual HTML page response, and not JSON or partial HTML in the case of an AJAX request. I would like to use the controller_action_layout_render_before event to determine that the head block is present, set a flag, which the previously mentioned observer method will check before modifying the response.

The use case is to safely prepend my custom block inside the head tag of every page, taking priority order over other head content such as meta tags, and script tags.

This is where I am at right now (not far, got a little lost)...

config.xml

<?xml version="1.0"?>
<config>
    ...
    <global>
        ...
        <events>
            <controller_action_postdispatch>
                <observers>
                    <intercept_response>
                        <class>module/observer</class>
                        <method>interceptResponse</method>
                    </intercept_response>
                </observers>
            </controller_action_postdispatch>
            <controller_action_layout_render_before>
                <observers>
                    <check_response>
                        <class>module/observer</class>
                        <method>checkResponse</method>
                    </check_response>
                </observers>
            </controller_action_layout_render_before>
        </events>
    </global>
    ...
</config>

Model/Observer.php

class My_Module_Model_Observer {

    protected $_isHead = FALSE;

    public function checkResponse() {
        if ( Mage::app()->getLayout()->getBlock('head')) {
            $_isHead = true;
        }
    }

    public function interceptResponse(Varien_Event_Observer $observer) {
        $block = $observer->getBlock();
    }

}
1

This will work (pay attention to caching though), but I would suggest a different and simpler approach: observe core_block_abstract_tohtml_after, check if the block's getNameInLayout() returns "head" and if yes, modify the content like this:

$html = $observer->getTransport()->getHtml();
// modify $html here...
$observer->getTransport()->setHtml($html);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.