Is there a way to change the template file of a block through code? I understand overriding the template file in theme but I want to override it on some condition.


You can use plugin on getTemplate() Method for override a phtml file.

At Magento, if a block has a phtml file then it must be called getTemplate() method to render the Block outPut.So if you want to change template file on a conditioning base then you can use Plugin.

Create after Plugin afterGetTemplate() on getTemplate() function. changes the template as per as your condition.

Define plugin at di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <type name="{YourBlockClassFullnamewithNameSpace}">
        <plugin name="change_the_temnplate"

Plugin Class:

namespace {PluginNameSpace};

class {PluginClassname}

    public function afterGetTemplate(
        \YourBlockClassFullnamewithNameSpace} $subject,
    ) {
        return '{Vendorname}_{ModuleName}::{templateLocation}/{templateFilename}.phtml';
        return $templateFile;
| 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.