靜態塊(static block),僅包含一些靜態的html內容,不涉及數據庫存取,好比像:一些文字和圖片連接,網站頁腳部分等。創建static block很簡單,Magento後臺提供一個功能,能夠方便的建立、編輯、管理static block。能夠在【管理員後臺】》【CMS】》【Static Blocks】菜單找到。 php
創建了static block後,如何在前端界面顯示呢?一是在Magento的layout文件中配置,而後在模板文件.phtml中經過調用 getChildHtml('block_id')輸出爲html代碼。下面藉助在Magento中系統內置的一個靜態塊footer_links來講明。 html
首先,在cms.xml layout文件中設置靜態塊:前端
<default> <referencename="footer"> <blocktype="cms/block"name="cms_footer_links"before="footer_links"> <!-- The content of this block is taken from the database by its block_id. You can manage it in admin CMS -> Static Blocks --> <actionmethod="setBlockId"><block_id>footer_links</block_id></action> </block> </reference> </default>
而後,在模板文件footer.phtml中輸出:
// echo $this->getChildHtml(); echo $this->getChildHtml('footer_links');
另一種方式更簡單,不須要配置layout文件,就能夠直接在php代碼中輸出靜態塊內容: 數據庫
echo $this->getLayout()->createBlock('cms/block')->setBlockId('footer_links')->toHtml();
確實很簡單,但Magento在背後作了大量的工做,在文件app/code/core/Mage/Cms/Block/Block.php中,能夠看到這些辛苦的步伐:
/** * Cms block content * * @category Mage * @package Mage_Cms * @author Magento Core Team <core@magentocommerce.com> */ classMage_Cms_Block_Block extendsMage_Core_Block_Abstract { protectedfunction_toHtml() { if(!$this->_beforeToHtml()) { return''; } $html= ''; if($blockId= $this->getBlockId()) { $block= Mage::getModel('cms/block') ->setStoreId(Mage::app()->getStore()->getId()) ->load($blockId); if(!$block->getIsActive()) { $html= ''; } else{ $content= $block->getContent(); $processor= Mage::getModel('core/email_template_filter'); $html= $processor->filter($content); } } return$html; } }