Introduction
CMS Static Blocks are a very powerful feature in Magento 2 using which a block of UI elements can be re-utilized in several pages across a Magento 2 website. First, we must create a CMS Static Block in the Magento 2 backend, then the block can be called and displayed in different pages.
Creating a CMS Static Block in Magento 2
To create a CMS Static Block in Magento 2, follow the below steps.
- Login to Magento 2 Backend
- Go to Content -> Blocks and click on the Add New Block button.
- Fill the below information and click on the Save button.
- Enable Block: Toggle button to Enable or Disable the block.
- Block Title: Enter a title for the block.
- Identifier: Enter a unique identifier for the block.
- Store View: Select the store view where you want to display this block.
- Content: Add content for this block using the page builder.
After creating the block, it can be displayed in different pages across the Magento 2 website. Below are the different methods to call a CMS Static Block.
Method to call a CMS Static Block in a template file (.phtml) in Magento 2
To call the CMS Static Block in your template file (.phtml), you can use the below code and set the correct block_identifier.
<?php
echo $this->getLayout()->createBlock('Magento\Cms\Block\Block')
->setBlockId('block_identifier')->toHtml();
?>
Method to call a CMS Static Block in a layout file (.xml) in Magento 2
To call the CMS Static Block in your layout file (.xml), you can use the below code and set the correct block_identifier.
<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>
Method to call a CMS Static Block in any CMS Content.
The CMS Static block can also be called and displayed in another CMS Static Block or a CMS Page. To do so, simply use the below code in the CMS content and set the correct block_identifier.
{{block class="Magento\\Cms\\Block\\Block" block_id="block_identifier"}}
I hope this tutorial is helpful for you. For any queries, please leave a comment.