Programatically create Magento blocks and inject them into layout

Imagine a scenario where you wish to simply create a view file like custom-note.phtml and show this view file on some new url inside the Magento store. One way to do this is to create a CMS page and call that block from within CMS page. But what if you wish to create and append this block to other areas of Magento layout that are inaccessible from CMS page interface form admin? What if I want to add new div element under the breadcrumbs and append new block under it?

magento philosophy is to create block class under the /Block folder of your module, to create xml layout file under the theme /layouts folder (or to modify existing layout file) and so on. Anyway you turn it around you either need to have Block file or add/modify at least the entry to the layout files.

All this is OK if you are working on your own store so you have full control over the code. However, what if you are developing a module that will be used on different Magento stores. My prime concern when building a module is to keep the number of necessary module files to a minimum.

In code below, you will see how easy it is to call your Core/Template block to show on any area of Magento layout.

Extracted from app/code/local/ActiveCodeline/CustomOutputs/controllers/IndexController.php file.

public function indexAction()
{
//Get current layout state
$this->loadLayout();
 
$block = $this->getLayout()->createBlock(
'Mage_Core_Block_Template',
'my_block_name_here',
array('template' => 'activecodeline/developer.phtml')
);
 
$this->getLayout()->getBlock('content')->append($block);
 
//Release layout stream... lol... sounds fancy
$this->renderLayout();
}

Most IMPORTANT thing to keep in mind here is the “error handling”. If you assign a “invalid” block to ->append(), you will not (most likely) see an error but “nothing happend” situation.

Anyhow… hope the attached module (extension) will save you some headaches. I know it took me few hours of tracing and testing to get the grip of it.

Download ActiveCodeline_CustomOutputs extension.

Cheers.