Returning Blocks From Controllers Without Layout Attached in Magento

When working in the admin environment of Magento i had to add a controller action that was called by an Ajax request. The problem however is that all layout data is returned as well when calling

$this->renderLayout();

from the controller. So my next attempt was to try to render the block separately and adding it to the layout.

$this->_initCustomer();
$this->getResponse()->setBody(
  $this->getLayout()->createBlock('block/location')
    ->setCustomerId(Mage::registry('current_customer')->getId())
    ->setData('list', $list)
    ->setUseAjax(true)
    ->toHtml()
);

This kinda worked. But now i had no more control over the template used. Or maybe i missed that part. But i don’t like to specify my Block anyway Magento should pick this up automatically.

Solving this issue is actually quite easy. The only thing we need to do is change the layout structure of the module. We change the name to root. And that’s it!

    <block type="block/location" name="root" template="template/location"></block>

The name attribute tells Magento it is a root block so no need for the rest of the layout.

comments powered by Disqus