Magento flexibility allows you to display CMS blocks in a multitude of ways. However, for those of you with technical knowledge, there are only two options.
You can either call CMS blocks in the XML layout, or call them in the PHTML file. Today we'll focus of the second one.
Post Contents [hide]
Call CMS Block in PHTML File
To programmatically call the CMS block in .phtml template file use this code:
<?php
echo $this->getLayout()
->createBlock(\Magento\Cms\Block\Block::class)
->setBlockId('my_cmsblock_identifier') //replace my_cmsblock_identifier with real CMS bock identifier
->toHtml();
?>
Note: you need to create and enable a CMS block for this method to work. If the CMS block is disabled or does not exist, this code will not display any content.
Using createBlock method is fast but not ideal in terms of best practices.
So what you can do is add a CMS block into your block using layout. Use the following code in a proper layout XML handle file and don't forget to flush Magento cache once the layout is changed:
<referenceBlock name="my-main-phtml-block">
<block class="Magento\Cms\Block\Block" name="my-main-phtml-block-cms">
<arguments>
<argument name="block_id" xsi:type="string">my_cmsblock_identifier</argument>
</arguments>
</block>
</referenceBlock>
Display it in a PHTML file with the getChildHtml block method:
<?= $block->getChildHtml('my-main-phtml-block-cms') ?>
Display CMS Blocks Dynamically
Adding CMS blocks to a page is one thing. Constantly enabling, disabling and changing the blocks in the PHTML file is completely the other.
To reduce the manual work and optimize the process you can simply specify the dates when the block should be active.
will automatically enable and disable your CMS blocks according to the settings.