Magento – how load block in controller

blockscontrollers

I use the following code to load a block in controller

$this->loadLayout();
      if ($this->getLayout()->getBlock('checkout.cart1')) {
        $cartlink =  $this->getLayout()->getBlock('checkout.cart1')->toHtml();
      }
  1. Here the checkout.cart1 is block name.
  2. My layout file code is

    <quickbuy_index_index>  
    <reference name="content">
    <block type="checkout/cart" name="checkout.cart1">
    <action method="setCartTemplate"><value>checkout/cart1.phtml</value></action>
    <action method="setEmptyTemplate"><value>checkout/cart/noItems.phtml</value></action>
              .
              .
              .
    </block>
    </reference>
    </quickbuy_index_index>
    
  3. Here my tag is <quickbuy_index_index>

  4. Now the controller code not load my block .
  5. But When i put the layout code within <default> tag instead of <quickbuy_index_index> tag, the controller load the block. like this
<default>
<block type="checkout/cart" name="checkout.cart1">
<action method="setCartTemplate"><value>checkout/cart1.phtml</value></action>
<action method="setEmptyTemplate"><value>checkout/cart/noItems.phtml</value></action>
          .
          .
          .
</block>
</default>

6. How i load the block in controller from <quickbuy_index_index> tag.

  1. My problem is, When i put a block in <default> tag, the controller load it.
    when i put a same block in url tag (<quickbuy_index_index>) the controller not load it.

Best Answer

To load a block in controller file:

$block = $this->getLayout()->createBlock('checkout/cart')->setTemplate('checkout/cart1.phtml');
$html = $block->toHtml();