Magento - 从xml获取块属性值的更好方法

时间:2012-11-23 14:17:22

标签: magento magento-1.7

设置数据:

<block type="obishomeaddon/customcategory" name="customcategory" template="homeaddon/customcategory.phtml">
        <action method="setData"> <name>column_count</name> <value>4</value> </action>
        <action method="setData"> <name>category_id</name> <value>116</value> </action>
      </block>

获取数据:

class Block extends Mage_Core_Block_Template {
   public getColumnCount() { 
     return $this->getData('column_count');
   }

   public getCategoryId() { 
     return $this->getData('category_id');
   }
}

但是我看到Magento可以做这样的事情:

<block type="obishomeaddon/customcategory" column_count="4" category_id="116" name="customcategory" template="homeaddon/customcategory.phtml"/>

如何从这种设置数据中设置属性值?

1 个答案:

答案 0 :(得分:2)

如果查看Mage_Core_Model_Layout->_generateBlock()(负责生成块的类),您将看到无法执行此操作。但是,添加它会非常简单。您可以覆盖Mage_Core_Model_Layout->_generateBlock(),如下所示:

config.xml文件中:

<models>
    <core>
        <rewrite>
            <layout>Namespace_Module_Model_Core_Layout</layout>
        </rewrite>
    </core>
</models>

然后,在您的文件中:

<?php

class Namespace_Module_Model_Core_Layout extends Mage_Core_Model_Layout
{
    protected function _generateBlock($node, $parent)
    {
        parent::_generateBlock($node, $parent);
        //   Since we don't want to rewrite the entire code block for 
        //   future upgradeability, we will find the block ourselves.

        $blockName = $node['name'];

        $block = $this->getBlock($blockName);
        if ($block instanceof Mage_Core_Model_Block_Abstract) {

            // We could just do $block->addData($node), but the following is a bit safer
            foreach ($node as $attributeName => $attributeValue) {
                if (!$block->getData($attributeName)) {
                    // just to make sure that we aren't doing any damage here.                    
                    $block->addData($attributeName, $attributeValue);
                }
            }
        }
    }
}

你可以做的另一件事,无需重写,缩短你的XML是这样的:

<block type="obishomeaddon/customcategory" name="customcategory" template="homeaddon/customcategory.phtml">
    <action method="addData"><data><column_count>4</column_count> <category_id>116</category_id></data></action>
</block>