update layout programmatically in magento event observer

后端 未结 5 969
陌清茗
陌清茗 2020-12-23 23:43

I am trying to change the template(view.phtml) of a block (product.info) for product detail page, to do this, I am observing an event (controller_action_l

5条回答
  •  执笔经年
    2020-12-24 00:12

    As Ben said, I don't know why you're going to put it on the observer but the problem in your case is the sequence of loadLayout.

    You can check your loaded layout xml by using:

    Mage::log(Mage::getSingleton('core/layout')->getUpdate()->asString());

    Pretty sure your has been overridden by other setTemplate that's the reason your template is not shown.

    Mage_Core_Controller_Varien_Action
    
    public function loadLayout($handles=null, $generateBlocks=true, $generateXml=true)
    {
        // if handles were specified in arguments load them first
        if (false!==$handles && ''!==$handles) {
            $this->getLayout()->getUpdate()->addHandle($handles ? $handles : 'default');
        }
    
        // add default layout handles for this action
        $this->addActionLayoutHandles();
    
        $this->loadLayoutUpdates(); //in here: $this->getLayout()->getUpdate()->load();
    
        if (!$generateXml) {
            return $this;
        }
        //event: controller_action_layout_generate_xml_before
        $this->generateLayoutXml(); //in here: $this->getLayout()->generateXml();
    
        if (!$generateBlocks) {
            return $this;
        }
        //event: controller_action_layout_generate_blocks_before, your observer is located here
        $this->generateLayoutBlocks(); //in here: $this->getLayout()->generateBlocks();
        $this->_isLayoutLoaded = true;
    
        return $this;
    }
    

    So, you're going to modify the xml using event: controller_action_layout_generate_blocks_before.

    It means what you need to do is:

    //add the update
    $layout->getUpdate()->addUpdate('');
    //then generate the xml
    $layout->generateXml();
    

    What cause your problem is:

    $layout->getUpdate()->load();

    was called again after

    $layout->getUpdate()->addUpdate('');
    

    Though it is better to use event: controller_action_layout_generate_xml_before. So that you don't need to generate your xml twice.

提交回复
热议问题