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.