2

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.

0

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"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="{YourBlockClassFullnamewithNameSpace}">
        <plugin name="change_the_temnplate"
                type="{YourPluginClass}"/>
    </type>
</config>

Plugin Class:

<?php
namespace {PluginNameSpace};

class {PluginClassname}
{


    public function afterGetTemplate(
        \YourBlockClassFullnamewithNameSpace} $subject,
        $templateFile
    ) {
        if({YourCondtion}){
        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.