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.
<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
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
<plugin name="very-unique-name" type="QaisarSatti\HelloWorld\Plugin\Block" />
</type>
And then create a class QaisarSatti\HelloWorld\Plugin\Block with content like
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).