0

Generally, in Magento 2, .phtml files have $block->getChildHtml(), allowing us to put extra data in the .phtml by adding a child to the layout.

If some .phtml file don't have such code and we want to put our custom HTML in a specific area, is there an approach to do that? Because overriding the .phtml file in the module will require frequent updates when the original .phtml file is updated.

I am seeking a way to add $block->getChildHtml('custom_block_name') in the .phtml before it renders.

Is there any way to do that?

(For example, I need to add block phtml under the customer name on the registration page.)

1
  • The only way to do that would be to render the element in a hidden container and then move it to the desired place by using javascript. Why are you not allowed to override the phtml file?
    – Black
    Commented Aug 2 at 15:05

2 Answers 2

0

One solution is adding the rendering of your block in the toHtml() class that renders the original block:

class View extends \Magento\Catalog\Block\Product\View {

   public function toHtml() {

    $output = $this->getLayout()->createBlock(\Magento\Cms\Block\Block::class)->setBlockId('blog-engagement')->toHtml();
    $output .= parent::toHtml();
    return $output;
   }

}

Remember to setup the preference for this class inside your module to make it work.

2
  • It will not place content in a specific place.
    – 26vivek
    Commented Aug 2 at 13:48
  • You can change the CMS block for whatever you are going to add into the original getChildHtml() call. This prepends your code (by a block or a hardcoded string) before the contents of the parent's gets added. Do you need to add your content in a specific section of the template?
    – Serfe
    Commented Aug 2 at 14:07
0

Please try using a layout update file

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="product_view">
        <block class="Magento\Catalog\Block\Product\View" name="product.info" template="Your_Module::product/view.phtml" />
    </update>
</page>

Thank You!

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.