1

In an existing observer, I would like to conditionally add a layout file to be parsed for cms_pages. I am already able to determine that the request is for a cms_page, and I then add a unique, custom handle to it so that I can forego using the cms_page.custom_layout_xml data-field, among other reasons. Hopefully that explains why I would want to apply it only to the pages to which it applies. I have found a few sources like this one that pointed me in a promising direction, but adding layout is limited to the actual xml-string, rather than parsing a file. Here is the code I have...

app/code/local/Vendor/Layout/etc/config.xml:

<?xml version="1.0"?>
<config>
    <modules>
        <Vendor_Layout>
            <version>0.1.0</version>
        </Vendor_Layout>
    </modules>
    <frontend>
        <events>
            <controller_action_layout_load_before>
                <observers>
                    <vendor_observer>
                        <class>Vendor_Layout_Model_Observer</class>
                        <method>controllerActionLayoutLoadBefore</method>
                    </vendor_observer>
                </observers>
            </controller_action_layout_load_before>
        </events>
    </frontend>
</config>

app/code/local/Vendor/Layout/Model/Observer:

<?php
class Vendor_Layout_Model_Observer {
    public function controllerActionLayoutLoadBefore(Varien_Event_Observer $observer) {

        $update = $observer->getEvent()->getLayout()->getUpdate();
        $handles = $update->getHandles();

// determine if it is a cms_page    
        if(in_array('cms_page', $handles)) {

// create and add unique handle
            $identifier = 'cms_page_'.str_replace('/', '_', Mage::getSingleton('cms/page')->getIdentifier());
            $update->addHandle($identifier);

// parse layout file and add it
            $filename = Mage::getSingleton('core/design_package')->getLayoutFilename('vendor/cms_page.xml');
            $cmsLayoutUpdate = file_get_contents($filename);
            $update->addUpdate($cmsLayoutUpdate);
        }
    }
}

Results: The entire file is added, producing an error if the <?xml version="1.0"?> tag is included in layout/vendor/cms_page.xml and if I remove the tag, the the file is added with the handles included which prevents the rules from being processed.

I tried using substring and strpos/strrpos to isolate the xml-string between the handle, but that has to be wrong because I would basically be reinventing the wheel. Any help is appreciated!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.