Magento 1.8 – Difference Between getChildHtml and getBlockHtml

blockslayoutmagento-1.8static-blocktemplate

Synopsis

  • What is the difference between getChildHtml and getBlockHtml?
  • How can I get the cms/block title in the template?

I have essentially replaced the footer with my own footer and set my own <?= $this->getChildHtml('...') ?> This didn't work until I used: <?= $this->getBlockHtml('...') ?>.

Layout XML:

<layout>
    <default>
        <block type="core/template" name="custom_footer" as="footer" template="page/html/footer.phtml">
            <block type="cms/block" name="child_1">
                <action method="setBlockId"><block_id>footer_child_1</block_id></action>
            </block>
         </block>
    </layout>
</default>

Template (doesn't work):

<footer>
    <div class="row">
        <div class="col-sp4"><?= $this->getChildHtml('child_1') ?></div>
    </div>
</footer>

Template (Works):

<footer>
    <div class="row">
        <div class="col-sp4"><?= $this->getBlockHtml('child_1') ?></div>
    </div>
</footer>

Solution:

First of all I had to override the footer inside my local.xml by:

<default>
    <block type="core/template" template="page/html/custom_footer.phtml" name ="custom_footer" as "footer" />
</default>

The I had to add my children (in order for getChildHtml() to work):

<reference name="footer">
    <block type="cms/block" name="child_1">
         <action method="setBlockId"><block_id>footer_child_1</block_id></action>
    </block>
</reference>

Best Answer

getBlockHtml('block_name_here') get's you the html of the block with name block_name_here if it finds it in the layout...anywhere.
getChildHtml('block_name_here') get's you the html of the block with name block_name_here only if that block is a child of the current block.

Here is an example. Consider the next layout section

<block type="core/template" template="some_template.phtml" name="some_name" />
<block type="core/template" template="some_other_template.phtml" name="some_other_name" />

Now in the template file some_template.phtml if you add this line of code <?php echo $this->getBlockHtml('some_other_name')?> you will get the html for the block some_other_name.
If you add <?php echo $this->getChildHtml('some_other_name')?> you will get nothing.

IN the following scenario

<block type="core/template" template="some_template.phtml" name="some_name">
    <block type="core/template" template="some_other_template.phtml" name="some_other_name" />
</block>

getChildHtml and getBlockHtml will get you the same thing. the html of the block some_other_name.

Related Topic