Magento Tutorials

Understanding Magento getChildHtml Method

The Magento getChildHtml method is the real power of blocks/templates. It allows you to render all the blocks inside a secondary block(“child”). inside of a primary block (“parent”). Blocks calling blocks calling blocks is how the entire HTML layout for your page is created.

Format:

<?= $block->getChildHtml('block_name'); ?>

Notes: Use $block instead of $this in PHTML template files, since the use of $this, according to Magento 2 Coding Standards, is discouraged

If the command can find block_name in template files anywhere, it will get you the HTML of block_name, that is only if block_name is a child of the current block.

For example, let’s take a look at an excerpt of the template file (view.phtml) for module-wishlist:

<?php if ($this->helper(\Magento\Wishlist\Helper\Data::class)->isAllow()) : ?>
    <div class="toolbar wishlist-toolbar"><?= $block->getChildHtml('wishlist_item_pager'); ?></div>
    <?= ($block->getChildHtml('wishlist.rss.link')) ?>

Here we can see the <div> class wishlist-toolbar has its content rendered by the blocks: wishlist_item_pager and wishlist.rss.link. These blocks are child blocks and are defined in wishlist_index_index.xml (located in vendor\magento\module-wishlist\view\frontend\layout\):

<referenceContainer name="content">
            <block class="Magento\Wishlist\Block\Customer\Wishlist" name="customer.wishlist" template="Magento_Wishlist::view.phtml" cacheable="false">
                <block class="Magento\Theme\Block\Html\Pager" name="wishlist_item_pager"/>
                <block class="Magento\Wishlist\Block\Rss\Link" name="wishlist.rss.link" template="Magento_Wishlist::rss/wishlist.phtml"/>
                </block>
		        </block>
	        </block>
</referenceContainer>

Note: The Magento getChildHtml method can only include blocks that are specified as sub-blocks (child) in the Layout. This allows Magento to only instantiate the blocks it needs, and also allows you to set different templates for blocks based on context.