Magento – Magento 2 | When to use referenceContainer and when referenceBlock

blockscontainersmagento2reference

I am getting same output if I use

referenceContainer

or

referenceBlock

As

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="order_totals">
        <block class="VendorName\ModuleName\Block\Sales\Totals" name="fee_amount" as="fee_amount"/>
    </referenceBlock>
</body>
</page>

And

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceBlock name="order_totals">
        <block class="VendorName\ModuleName\Block\Sales\Totals" name="fee_amount" as="fee_amount"/>
    </referenceBlock>
</body>
</page>

Layout File is:

VendorName\ModuleName\view\frontend\layout\sales_order_view.xml

I am curious, which is recommended to use. If both can work, then on what specific conditions?
I understand basic of container as explained here.

Best Answer

Following are major difference between both of them:

Container: Using container we can create a new blank HTML dom using htmlClass and htmlDiv attribute of container. This is to create a blank HTML dom.

ReferenceContainer: There is already a container exist and you want to put your block or container in that container we use referenceContainer tag.

Block: Block works as mediator of our phtml file and the business logic. In block we define the PHP class and the phtml file path and it works to connect both of them. In PHTML file if call the function of block class that is provided in class attribute of tag.

ReferenceBlock: ReferenceBlock is used when we want to use already existing block and want to put our block in that existing block. We use this if we want to add changes to phtml file of that block. In the PHTML file of existing block we use $block->getChild('name_of_child_block') function to render the output of child block.

For more details you can follow documentations:

https://devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/xml-instructions.html

If hope this will clear you concept about the block/container and referenceBlock/referenceContainer.

Related Topic