Skip to content

best practice for get a block by id in *.phtml template in 2022 year?

Can you help me figure out which best practices to use for get block template by id in phtml file?
thanks everyone

if you need some info please send comment


okay, try it:

  • i created a block in admin panel with id bottom-content and the block will be show in frontend
  • i trying to get block template in *.phtml with the code:
<?php 

echo $this->getLayout()
    ->createBlock('MagentoCmsBlockBlock')
    ->setBlockId('bottom-content')
    ->toHtml(); 
?>

but i know that is not best practice. sure best practice is it call block in *.xml

  • then my code look this:
<referenceBlock name="content">
    <referenceBlock name="bottom.content">
        <block class="MagentoCmsBlockBlock" name="bottom.content">
            <arguments>
                <argument name="block_id" xsi:type="string">bottom.content</argument>
            </arguments>
        </block>
    </referenceBlock>
</referenceBlock>
  • And in this case my *.phtml look this:
<?= $this->getChildHtml('bottom-content'); ?>

But when i open a site i observe this error:

Exception #0 (MagentoFrameworkExceptionLocalizedException): An element with a “bottom.content” ID already exists.

How can i fix it?