0

In my template I iterate over a collection of 4 simple products. Each time I call

$this->getChildHtml('myblock', false)

Depending on the settings of the simple products there is always another content that should be loading. But only the first block is correct. The other blocks have always the same content as the first one.

I use no magento cache to develop. What magic is magento using here?

0

There is no magic taking place. When you call upon $this->getChildHtml('myblock', false), there is nothing telling the child block you are trying to render that it needs data from the product within your loop, so it's just going to call the same block over and over again.

If you want to render the block slightly different for each product that you iterate over, $this->getChildHtml('myblock', false) is probably not the way to go.

What you need to do is create a separate instance of the block, set the product object on the block, and then call the block's toHtml() method.

In the most basic example possible, you can do it like this:

<?php    

$collection = Mage::getModel('catalog/product')->getCollection();
foreach($collection as $product){
    $block = $this->getLayout()->createBlock('core/template');
    $block->setProduct($product);
    $block->setTemplate('some/template/file.phtml');
    echo $block->toHtml();
}

Within some/template/file.phtml you would access the product object like this: $product = $this->getProduct(); and from there you can do whatever you need to.

I should also mention that the code in the loop in which I create the block should really be wrapped up into a function within your custom block's class. In other words, that code is for example to show you how it's done but I wouldn't put the block creation code directly into your template file. Instead, wrap it up into a function that accepts the product as an argument and call upon that custom function within your template file.

1
  • @Tipo did my answer help you? – Shawn Abramson Aug 13 '16 at 4:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.