Chris
Chris

Reputation: 1400

How do I call a block in a phtml instead of through a layout?

I have disabled layout for the wishlist block:

<block type="catalog/product_view" name="product.info.addtoto" as="addtoto" template="catalog/product/view/addto.phtml"/>

I now want to call that block in the phtml instead of add it to another layout.

How do I call it directly?

Upvotes: 8

Views: 32623

Answers (4)

Charlie Tupman
Charlie Tupman

Reputation: 529

I struggled with this for ages and found that if you want to call a block from a totally separate part of the layout you need to use slightly different code. Use:

<?php echo $this->getBlockHtml('any_block'); ?>

Instead of:

<?php echo $this->getChildHtml('any_block'); ?>

Using this code you can either create your own blocks anywhere or pick blocks from other modules and put them anywhere.

Upvotes: 3

Joe Mastey
Joe Mastey

Reputation: 27119

While Prattski is correct that this is poor form (am I'm upvoting as such), there have been times when developing when either this has been a valuable debugging technique, or it made the difference of several hours of programming. In that spirit, this is the bad habit way of doing it:

<?php print $this->getLayout()
                 ->createBlock("catalog/product_view")
                 ->setTemplate("catalog/product/view/addto.phtml")
                 ->toHtml(); ?>

Use sparingly, if at all.

Upvotes: 31

R T
R T

Reputation: 4549

 echo  Mage::app()->getLayout()
        ->createBlock('somemodule/someblock')
        ->setSomeVariable($variable)
        ->setTemplate('somemodule/someblock.phtml')
        ->toHtml();

this can be use anywhere for calling blocks. setSomeVariable($variable) if set can be accessed in someblock.phtml by $this->getSomeVariable();

Upvotes: 12

Prattski
Prattski

Reputation: 2060

Chris - You should ever need to call a block directly from within a template. It would be a bad habit/practice to get into. Find the proper reference to the template you want to add the block to, and add it into the layout xml. Then from within the template file, use:

echo $this->getChildHtml('your-block');

Upvotes: 3

Related Questions