2

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('Magento\Cms\Block\Block')
    ->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="Magento\Cms\Block\Block" 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 (Magento\Framework\Exception\LocalizedException): An element with a "bottom.content" ID already exists.

How can i fix it?

0

3 Answers 3

3

As \Magento\Cms\Block\Block is deprecated, you should use the \Magento\Cms\Block\BlockByIdentifier

Example in phtml

<?= $this->getLayout()
            ->createBlock(BlockByIdentifier::class)
            ->setData('identifier', 'return_page_description')
            ->toHtml();
        ?>
0

You are declaring 2 blocks with the same name, so you face that error.

To fix it, replace your XML file with the following:

<referenceBlock name="content">
    <block class="Magento\Cms\Block\Block" name="bottom.content">
        <arguments>
            <argument name="block_id" xsi:type="string">bottom-content</argument>
        </arguments>
    </block>
</referenceBlock>

And you also declare the wrong value for block_id argument and call the wrong block name in the phtml file. Replace your code in phtml file to call the call with the following:

<?= $this->getChildHtml('bottom.content'); ?>

0
0

Add Below code in your Phtml file

<?php
        echo $this->getLayout()
            ->createBlock('Magento\Cms\Block\Block')
            ->setBlockId('set_identifier') // you can set block identifier you want here
            ->toHtml();
        ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.