Magento 2 override phtml file in custom module

Today we talk about how to override the magento 2 phtml file in custom module. First thing is simple just create xml file default.xml in your module layout folder. Then call the referenceBlock name you want to override in your module. There is two possible way to do that.

First:

Using the layout file to override the phtml file. You must be aware of block name of phtml file. Now use below simple code to override.

<referenceBlock name="block-name">
    <action method="setTemplate">
        <argument name="template" xsi:type="string">QaisarSatti_HelloWorld::path/to/my/file.phtml </argument>
    </action>
</referenceBlock>

Note
This solution requires finding all instances where the block is used and create as many xml files as handles in which it is used.
As come to my knowledge setTemplate is decrpted method so here is latest code

<referenceBlock name="block-name" template="QaisarSatti_HelloWorld::path/to/my/file.phtml"/>

Second:

The block is used very often or you want to make sure each new user will not require adding this kind of configuration you can do it using the plugin.

Declare your plugin either in etc/di.xml or etc/frontend/di.xml

<type name="Other\Module\Block">
    <plugin name="very-unique-name" type="QaisarSatti\HelloWorld\Plugin\Block" />
</type>

And then create a class QaisarSatti\HelloWorld\Plugin\Block with content like

<?php
namespace QaisarSatti\HelloWorld\Plugin;

class Block
{
    public function beforeToHtml(\Other\Module\Block $block)
    {
        $block->setTemplate('QaisarSatti_HelloWorld::path/to/my/file.phtml');
    }
}

Note:
This way you enforce the use of this template in each instance so you will be no longer available to set it different just for 1 usage in the layout XML file (unless you will add some flag to the block and logic to check it in the plugin).

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply