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 are two possible way to do that.
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.
<argument name="template" xsi:type="string">'QaisarSatti_HelloWorld::path/to/my/file.phtml </argument>
This solution requires finding all instances where the block is used and create as many xml files as handles in which it is used.
The block is used very often or you want to make sure each new usage will not require adding this kind of configuration you can do it using plugin.
Declare your plugin either in etc/di.xml or etc/frontend/di.xml
<plugin name="very-unique-name" type="QaisarSatti\HelloWorld\Plugin\Block" />
And then create a class QaisarSatti\HelloWorld\Plugin\Block with content like
public function beforeToHtml(\Other\Module\Block $block)
This way you enforce use of this template in each instance so you will be no longer available to set it different just for 1 usage in layout xml file (unless you will add some flag to the block and a logic to check it in the plugin).
Last Modified: July 12, 2018