4

What is the way to override a phtml of a custom module from another custom module.

8

There are 2 possible ways:

1) Using layout xml files like:

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

This solution requires finding all instances where the blok is used and create as many xml files as handles in which it is used. If 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.

2) Plugin usage. Declare your plugin either in etc/di.xml or etc/frontend/di.xml

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

And then create a class My\Module\Plugin\Block with content like

namespace My\Module\Plugin;

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

This way however 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 layout xml file (unless you will add some flag to the block and a logic to check it in the plugin).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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