Magento 2 – How to display a CMS block in a PHTML file

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>
Can a CMS block be called conditionally?

Yes. You can add any PHP logic to the .phtml file, e.g., checking: product type, a given product feature, a customer attribute, etc.).

Does this solution work in Magento 2.4.x?

Yes. All described methods are compatible with Magento 2.4.x

Why is it worth using a CMS block instead of static HTML?

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).

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *