2012-11-23 78 views
1

設置數據塊的屬性值:Magento的 - 更好的方式來獲得XML

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

如何從這種設置數據中設置屬性值?

回答

2

如果你看Mage_Core_Model_Layout->_generateBlock()(負責生成塊的類),你會發現這是不可能的。然而,這將是非常簡單的將其添加到您可以覆蓋Mage_Core_Model_Layout->_generateBlock()這樣的:

在你​​3210文件:

<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> 
+0

謝謝f或者很好的回答:) – nXqd

+0

樂意幫忙! :) –

相關問題