Magento 2 Override – How to Override final_price.phtml in Magento 2

magento2overridesprice

I want to override final_price.phtml, I have tried following in my module but it is not working.
I have created app/code/MyVendor/MyModule/view/frontend/layout/catalog_product_prices.xml

<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd">
    <referenceBlock name="render.product.prices">
        <arguments>
            <argument name="default" xsi:type="array">
                <item name="prices" xsi:type="array">
                    <item name="final_price" xsi:type="array">
                        <!-- item name="render_class" xsi:type="string">Magento\Catalog\Pricing\Render\FinalPriceBox</item> -->
                        <item name="render_template" xsi:type="string">MyVendor_MyModule::product/price/final_price.phtml</item>
                    </item>
                </item>
            </argument>
        </arguments>
    </referenceBlock>
</layout> 

Also I have created template file as well. at app/code/MyVendor/MyModule/view/frontend/templates/product/price/final_price.phtml
And in final_price.phtml I wrote my custom code.

But it is not working.
Can anyone tell me what is missing in this code?

Best Answer

You can use alternative way for overriding template. Use below code. It will work.

app/code/MyVendor/MyModule/etc/di.xml

<type name="\Magento\Catalog\Pricing\Render\FinalPriceBox">
        <plugin name="MyVendor_MyModule_change_template" type="MyVendor\MyModule\Plugin\FinalPricePlugin" />
</type>

MyVendor\MyModule\Plugin\FinalPricePlugin.php

<?php
namespace MyVendor\MyModule\Plugin;

class FinalPricePlugin
{
    public function beforeSetTemplate(\Magento\Catalog\Pricing\Render\FinalPriceBox $subject, $template)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $enable=$objectManager->create('MyVendor\MyModule\Helper\Data')->chkIsModuleEnable();
        if ($enable) {
            if ($template == 'Magento_Catalog::product/price/final_price.phtml') {
                return ['MyVendor_MyModule::product/price/final_price.phtml'];
            } 
            else
            {
                return [$template];
            }
        } else {
            return[$template];
        }
    }
}

Hope it will work for you.

Related Topic