Accessing Static Blocks In Magento

piaoling  2011-06-23 18:58:24

Sometimes a client asks to be able to manage certain areas of their Magento ecommerce website that would usually require access to template files. While this is okay, most clients consider HTML a foreign language and would probably do more harm than good. To remedy this, a lot of developers would consider creating a custom module. While this isn't bad, sometimes it can require too much work if the client only wants to change one line of text! A much easier and quicker solution is to use a static block. Static Blocks can be included into your design in three main ways:

  • Inside a template file using PHP
  • Inside a content field of a CMS Page in the Magento admin
  • Inside the Layout Update XML field of a CMS page in the Magento admin

Accessing a Magento Static Block From a PHP Template File

To access the block's content from a .phtml template file, use the following code.

?
1
2
$block = Mage::getSingleton('core/layout')->createBlock('cms/block')->setBlockId('block-id-in-magento');
echo $block->toHtml();

Copy the above code into a Magento template file, obviously changing your 'block-id-in-magento' to the static block you want to include.

Accessing a Magento Static Block From A CMS Page

If you have created a CMS page in the Magento administration, sometimes you may want to add a static block inside of it. To accomplish this, you could either add a line of code into the content field or add it to the custom layout xml field.

Add a Static Block to the CMS Page Content Field

?
1
{{block type="cms/block" block_id="block-id-in-magento"}}

Adding a Static Block to the CMS Page Layout Update XML FIeld

?
1
2
3
4
5
<reference name="content">
  <block type="cms/block" name="block.name">
    <action method="setBlockId"><block_id>block-id-in-magento</block_id></action>
  </block>
</reference>

Magento Static Blocks: Conclusion

This tutorial is short but hopefully illustrates the many ways of accessing static blocks programmatically. Each method has it's advantages and disadvantages so consider which one is best for the functionality you are trying to achieve.

This post was posted in General

1 Response to Accessing Static Blocks In Magento

JP says:

"Each method has it’s advantages and disadvantages so consider"

Could you elaborate on what those might be? I'm very new to Magento (but not PHP) and I'm struggling to find my way around this monster.

Also, is there a reference for the XML structure? I've looked at countless Magento xml layout files and am still confused as to what goes where and why. Does this XML mess come from Zend, or is it a Magento construct devised to weed out the weak?!

类别 :  magento(258)  |  浏览(3802)  |  评论(0)
发表评论(评论将通过邮件发给作者):

Email: