Magento 2: How to Override Template using Helper Function

Magento 2 How to Override Template using Helper Function

Hello Magento Friends,

In today’s blog, we will find out how to override template using helper function in Magento 2.

Magento 2 provides a flexible architecture where developers can customize the default functionality based on their needs. One such customization is overriding the template file. Overriding template file allows to modify how content is displayed in frontend.

Let’s perform the steps to override template file using helper function in Magento 2.

Steps to Override Template using Helper Function in Magento 2:

Step 1: First, we need to create a catalog_category_view.xml file inside the extension at the following path.

app\code\Vendor\Extension\view\frontend\layout\

Note: You can create any xml file which you want to override.

Now add the code as follows

<?xml version=”1.0″?>

<page xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:View/Layout/etc/page_configuration.xsd”>

<body>

<referenceBlock name=”category.description”>

            <action method=”setTemplate”>

                <argument name=”template” xsi:type=”helper” helper=”Vendor\Extension\Helper\Data::getTemplate”></argument>

            </action>

</referenceBlock>

</body>

</page>

Step 2: After that, we need to create a Data.php file inside the extension at the following path.

app\code\Vendor\Extension\Helper\

And add the code as given below

<?php

namespace Vendor\Extension\Helper;

public function getTemplate()

{

     if(set_your_condition_here){

      $template =  ‘Vendor_Extension::category/description.phtml’;

     }

     else{

      $template =  ‘Magento_Catalog::category/description.phtml’;

     }

     return $template;

}

Step 3: After that, we need to create a description.phtml file inside the extension at the following path.

app\code\Vendor\Extension\view\frontend\templates\category\

Now, modify the template as per your need.

<?php if ($_description = $block->getCurrentCategory()->getDescription()) :?>

    <div class=”category-description helper-override”>

        <?= /* @noEscape */ $this->helper(Magento\Catalog\Helper\Output::class)->categoryAttribute(

            $block->getCurrentCategory(),

            $_description,

            ‘description’

        ) ?>

    </div>

<?php endif; ?>

Conclusion:

This way you can override template using helper function in Magento 2. Got any questions or need help with Magento 2 customizations? Feel free to reach out!

Previous Article

How to Add an App Force Update Popup in React Native?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨