1

设置数据:

<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"/>

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

4

1 回答 1

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>
于 2012-11-23T15:04:25.183 回答