Magento: how to create a child block programmatically?
-
25-06-2021 - |
Question
I have a page that has some template block included programmatically as follows:
public function indexAction() {
$this->loadLayout();
$block = $this->getLayout()
->createBlock('core/template')
->setTemplate('somefolder/sometemplate.phtml');
$this->getLayout()->getBlock('content')->append($block);
$this->renderLayout();
}
I would like to put inside the sometemplate.phtml, $this->getChildHtml('somechild') to insert another block.
I tried to
$box = $this->getLayout()
->createBlock('page/html')
->setTemplate('somefolder/somechild.phtml');
$block->append($box);
But didn't work. How can I do it?
Solution
I solved the problem by using setChild method as follows:
$block->setChild('somealias',$childBlock);
And so I can use
<?php echo $this->getChildHtml('somealias'); ?>
OTHER TIPS
To add up to Ricardo Martins's answer
If you need it in a block directly you can do what product price does
Mage_Catalog_Block_Product
:
public function getPriceHtml($product)
{
$this->setTemplate('catalog/product/price.phtml');
$this->setProduct($product);
return $this->toHtml();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow