Hello Friends!!!
In this blog, we are going to learn how we can override a phtml file in referenceBlock dynamically in the layout file.
For example, we have created a layout file custommodule_index_index.xml inside the app/code/Vendor/Custommodule/view/frontend/layout/ directory. Now, we have to override the block “custom_block_home”.
Then, we can override it by using the following methods:
Based on a check of the configuration field in the layout file: In this way, we add the “ifconfig” attribute in the “action” tag to set the template. Please look into the following code:
<?xml version="1.0"?> <!-- /** * Vendor * * @category Vendor * @package Vendor_Custommodule * @author Vendor * @copyright Vendor(https://example.com) * @license https://example.com/license.html */ --> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="blank" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="custom_block_home"> <action method="setTemplate" ifconfig="custommodule/configuration/isactive"> <argument name="template" xsi:type="string">Vendor_Custommodule::home.phtml</argument> </action> </referenceBlock> </body> </page>
Based on a method’s result: In this way, we can call a method from a helper file, and according to the result of the method, the template will be set in block dynamically. Please refer to the following code:
<?xml version="1.0"?> <!-- /** * Vendor * * @category Vendor * @package Vendor_Custommodule * @author Vendor * @copyright Vendor (https://example.com) * @license https://example.com/license.html */ --> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="blank" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="custom_block_home"> <action method='setTemplate'> <argument name="template" xsi:type="helper" helper="Vendor\Custommodule\Helper\Data::getHomeTemplate"> </argument> </action> </referenceBlock> </body> </page>
We have created the following method, in the Data.php file inside the app/code/Vendor/CustomModule/Helper/ directory.
/** * Get Home Template * * @return string */ public function getHomeTemplate() { $template = ""; $check = $this->isModEnabled(); //you can call here your method to get the result for required condition if ($check) { $template = 'Vendor_Custommodule::home.phtml'; } else { $template = 'Vendor_PrevCustommodule::home.phtml'; } return $template; }
Hope this will be helpful. Thanks 🙂
Be the first to comment.