Adding a Custom Block to Magento CMS Page
Adding a Custom Block to Magento CMS Page
Adding a custom block to Magento CMS page is a very good way to improve the flexibility of these static pages. This will help us to keep our CMS page tight, without copy-pasting the same large paragraph of scripts into every single page.
It’s usually an over-shoot to build a whole new module for this, a new block class would be sufficient for this purpose.
Since it’s CMS related, we can simply do the following:
- Extend the Magento core module: core/Mage/CMS
- Create local/Mage/Cms/Block/xxx.php
- Also create the corresponding .phtml template
- (No update needed for the layout/ folder)
Please make sure the block is extending Mage_Core_Block_Template, not the Mage_Core_Block_Abstract!
This is very important, because we want to use the default Magento behavior defined by [codesyntax lang=”php” lines=”fancy”]
protected function _toHtml(){...}
[/codesyntax]. Thus it is different from normal Magento core blocks, like Cms/Block/xxx.php files which extend Mage_Core_Block_Abstract and has their own _toHtml() function.
Such Magento core blocks usually handle special views, like the ones defined in the admin->static blocks or email templates. They are Not supposed to handle .phtml templates!. Here we need the default behavior of Mage_Core_Block_Template that can render the view of the .phtml file via _tohtml() function. (In case you have to extend Mage_Core_Block_Abstract, make sure the build your own _tohtml() to create an appropriate view. Otherwise nothing is going to show up.)
There are 2 easy ways to incorporate the new custom block in CMS page:
- Method 1: (In admin->CMS->General Info, directly add to “Content”)
[codesyntax lang=”html4strict” lines=”fancy”]
{{block type=”cms/featurebox” name=”home.cms.featurebox” template=”cms/featurebox.phtml”}}
[/codesyntax]
- Method 2: (In admin->CMS->Custom Design, directly add to “Layout update XML”)
[codesyntax lang=”xml” lines=”fancy”]
<reference name="content"> <block type="cms/featurebox" name="home.cms.featurebox" template="cms/featurebox.phtml"/> </reference>
[/codesyntax]
Overall, Method 1 is a much better way, plus it’s more flexible.