Yaroslav Rogoza Yaroslav Rogoza - 1 year ago 89
PHP Question

Magento. Insert block into another without change template code

I've tried to find solution but with no results.
My task is to write module. It should insert some html into existing block.

I noticed that when I used layout .xml files I can just insert my block into some reference like

<reference name="product.info">
<block type='googlethis/link' name="googlethis"

and my block shows as well.

In other cases I should call
method and it's not good because it makes to change template .phtml files.

So is there way to insert my phtml block into any other phtml block without calling

Jon Jon
Answer Source

There is a way to do this, although it is not an entirely elegant solution. It will work in most instances though and has proved helpful on occasion.

Basically the idea is that you replace the block you want to render your block before/after in your layout XML, place that block as a child in your block and then render it's output before/after yours.

So let's say you wanted to output a block before the totals block on the cart details page, you could do the following in your extension's layout.xml

    <reference name="checkout.cart">
        <block type="myextension/block" name="myextension.block" as="myextension_block" template="myextension/template.phtml">
            <action method="setChild"><name>totals</name><block>totals</block></action>
        <action method="setChild"><name>totals</name><block>myextension.block</block></action>

Then in your template.phtml file you would have:

<div id="myextension">
    // Your template code

// Render the totals block that you placed inside your block
<?php echo $this->getChildHtml('totals'); ?>

As I said, this won't fit every situation and it's not incredibly elegant, but it does work.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download