Month: May 2019

Understanding $block->getChildHtml()

As I am learning magento, I had this issue from quite a while. Sometimes I was able to use $block->getChildHtml and sometimes not. So I asked help from my colleague Lee and he helped me to understand the whole concept of $block->getChildHtml();
Supposably I want to display this block in one of my view which block of class ‘Title’

echo $block->getChildHtml('sudeep_block');

So in layout file I have to define this as follows

<!-- page title -->
<block class="Vendor\Product\Block\Html\Title" name="page.main.title"
       template="Magento_Catalog::product/view/title.phtml">
    <block class="Vendor\Product\Block\Html\Title" name="product.info.sudeep.block" as="sudeep_block"
           template="Magento_Catalog::product/view/sudeep_block.phtml"/>

</block>


If I don’t put this within <block class=”Vendor\Product\Block\Html\Title” ┬áit will not appear correctly. This is because, we are calling child HTML of this block
Thats the reply from my colleague Lee
“the problem with putting things in the product.info.main container is that its just a container and things are ordered within that container based on the before and after elements that are added in the xml – it just prints all the blocks out that are set.
I’ve moved it into the title block – this sets it as a child, so you can either call ->getChildHtml() – that will pull all child elements in that block
or ->getChildHtml(‘name-of-block’) – and that will call the specific block that you want
if its available obviously!”
Advertisements

Magento 2 add static block in Layout XML

Here is a quick way on how to add static cms block in the layout

Display CMS Static Block In Phtml File:

Here the code to show CMS Static Block in any template (phtml) file in Magento 2,



->createBlock('Magento\Cms\Block\Block')
->setBlockId('block_identifier')
->toHtml();
?>

Display CMS Static Block In CMS Content:

Here the code to show CMS Static Block in any other CMS static block/page in Magento 2,


{{block class="Magento\\Cms\\Block\\Block" block_id="block_identifier"}}

Display CMS Static Block In XML:
Here the code to show CMS Static Block in any layout (XML) file in Magento 2,

 

<referenceContainer name="content"> 
<block class="Magento\Cms\Block\Block" name="block_identifier"> 
<arguments> 
<argument name="block_id" xsi:type="string">block_identifier</argument> 
</arguments> 
</block> 
</referenceContainer>

 

 

Thanks to info at http://www.blogtreat.com/magento-2-how-to-call-cms-static-block-in-phtml-file/