Proper way to get $block->getChildHtml inside the custom phtml file
-
15-04-2021 - |
سؤال
I want to add default wishlist sidebar section into my Magento_Theme template,
Layout xml file:
<referenceBlock name="header.panel">
<block class="Magento\Framework\View\Element\Template" name="mylocation.block" template="Magento_Theme::location_link.phtml" after="-">
<!-- Wishlist sidebar section -->
<block class="Magento\Wishlist\Block\Customer\Sidebar" name="wishlist_sidebar" as="wishlist" template="Magento_Wishlist::sidebar.phtml"/>
</block>
</referenceBlock>
FYI : The following code coming from core vendor\magento\module-wishlist\view\frontend\templates\sidebar.phtml
<!-- Wishlist sidebar section -->
<block class="Magento\Wishlist\Block\Customer\Sidebar" name="wishlist_sidebar" as="wishlist" template="Magento_Wishlist::sidebar.phtml"/>
After added in layout xml file and getting this block using getChildHtml in app\desigh\frontend\Zero\my_theme\Magento_Theme\templates\location_link.phtml
<?php echo $block->getChildHtml('wishlist');?>
Not working, any help thanks.
المحلول
Your method is not working because your blocks are siblings and do not have a parent/child relationship. The key is the word child
in getChildHtml
.
If you nest your wishlist block inside the location block that will work.
Also, header.panel
is a container, not a block. See https://github.com/magento/magento2/blob/5e57ddd6b0452121e26ce93c74029cf58c4b1d6b/app/code/Magento/Theme/view/frontend/layout/default.xml#L34
<referenceContainer name="header.panel">
<block class="Magento\Framework\View\Element\Template" name="mylocation.block" template="Magento_Theme::location_link.phtml" after="-">
<!-- Wishlist sidebar section -->
<block class="Magento\Wishlist\Block\Customer\Sidebar" name="wishlist_sidebar" as="wishlistc" template="Magento_Wishlist::sidebar.phtml"/>
</block>
</referenceContainer>
نصائح أخرى
Try to move it instead:
<move element="wishlist_sidebar" destination="mylocation.block" before="-"/>
Also make sure to clear the cache, sometimes not even when running flush and clear cache, magento stop using cached. When it happens I need to clear static files. I recommend disable full_page and block_html cache while you working on it:
bin/magento c:d full_page
bin/magento c:d block_html