In Magento 2, CMS blocks are most often used directly in XML layouts. However, there are times when you need to display a CMS block directly in a PHTML file, for example, with conditional logic. In this post, we’ll explain how to properly invoke a CMS block in .phtml files.
Calling a CMS block in .phtml
<?php
echo $this->getLayout()
->createBlock('Magento\Cms\Block\Block')
->setBlockId('id_bloku_cms')
->toHtml();
?>
Instead of “cms_block_id” enter the static CMS block ID.
Important: enter the ID set on the panel side, not the ID from the database.
Calling a CMS block on a CMS page
If a CMS block is to be used inside the content of a CMS page, the following directive should be used:
{{block class="Magento\\Cms\\Block\\Block" block_id="id_bloku_cms"}}
Calling a static CMS block via an xml (layout) file
<referenceContainer name="product.info.main">
<block class="Magento\Cms\Block\Block" name="block_identifier">
<arguments>
<argument name="block_id" xsi:type="string">id_bloku</argument>
</arguments>
</block>
</referenceContainer>
Yes. You can add any PHP logic to the .phtml file, e.g., checking: product type, a given product feature, a customer attribute, etc.).
Yes. All described methods are compatible with Magento 2.4.x
Because the content placed in the CMS block does not require code deployment after a change and can be freely modified by the administrator (directly from the panel).
Leave a Reply