In Magento 2, you can override a template file using a helper function by dynamically specifying the custom template path in your custom helper class. This approach allows you to change the template file for a specific block without modifying the core block class.
Create dolphin_index_blog.xml in app/code/Dolphin/Customize/view/frontend/layout directory with the following code.
<?xml version="1.0" ?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="content"> <block name="index.blog" class="Dolphin\Customize\Block\Index\Index"> <action method="setTemplate"> <argument name="template" xsi:type="helper" helper="Dolphin\Customize\Helper\Data::getTemplate"></argument> </action> </block> </referenceContainer> </body> </page>
The helper can use only public methods. In this example the someMethod()
method should be public. The argument with helper type can contain param
items which can be passed as a helper method parameters.
we use the <action>
node to call the setTemplate
method of the block with the alias “index.blog” We pass the path to the custom template file obtained from the helper function as an argument using xsi:type="helper"
. This tells Magento to dynamically fetch the template path using the specified helper method.
Create Data.php in app/code/Dolphin/Customize/Helper directory with the following code.
<?php /** * Copyright © All rights reserved. * See COPYING.txt for license details. */ declare(strict_types=1); namespace Dolphin\Customize\Helper; use Magento\Framework\App\Helper\AbstractHelper; class Data extends AbstractHelper { /** * @param \Magento\Framework\App\Helper\Context $context */ public function __construct( \Magento\Framework\App\Helper\Context $context ) { parent::__construct($context); } public function getTemplate() { $template = 'Dolphin_Customize::index/blog.phtml'; return $template; } }
Create blog.phtml in app/code/Dolphin/Customize/view/frontend/templates/index directory with the following code.
<?php /** * dolphin index template * * @var $block \Dolphin\Customize\Block\Index\Index */ ?> <h2>blog templates</h2>
Now execute the below command and go to the system configuration page:
php bin/magento s:up
php bin/magento s:d:c
php bin/magento s:s:d -f
php bin/magento c:c
I Hope, This instruction will be helpful for you.
If you have any difficulties regarding this blog, do consider posting them in the Comments section below!
I’m here to help.
Thank you!