LinkedIn Twitter RSS Reset

Creating Block From the Code in Magento

Here are some methods of creating block by code in Magento. This type of code can be used directly in template, not need to create a layout file or add a child node inside already existing layout file. You can use this to echo a different type of block inside already loading block and template.

// Directly in the PHTML where you want to show the block
<?php
echo $this->getLayout()->createBlock("module/block")->setTemplate("module/page.phtml")->toHtml();
?>

What we have actually done is just load the layout and create an instance of a block class defined inside its paramerter, then assigned a template to the block and finally echoed as html. Simple! The code above will be equivalent to what we do as following in layout and in template file.

// In layout
<block type="module/block" name="module.name" template="module/page.html"/>
<?php
// In parent PHTML
$this->getChildHtml("module.name");
?>

May be helpful!

2 Responses to “Creating Block From the Code in Magento”

  1. Jagdish Bhandari
    January 11, 2012 at 4:30 am #

    Very nice Tutorial. Please keep carry on. Thanks.

  2. narendra
    May 11, 2012 at 8:48 pm #

    nice i get the right solution thanks!

Leave a Comment