Magento 2.2 – How to Override Price Renderer on Listing Pages via XML

magento2.2overridesxml

I am trying to override a price template, namely price_final.phtml.

etc/di.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Pricing\Render\PriceBox" type="Project\ProductPriceSaving\Block\Pricing\Render\PriceBox" />
</config>

etc/module.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Project_ProductPriceSaving" setup_version="0.1.0">
        <sequence>
            <module name="Magento_Catalog" />
        </sequence>
    </module>
</config>

view/frontend/layout/catalog_product_prices.xml

<?xml version="1.0"?>
<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="default_render_class" xsi:type="string">Project\ProductPriceSaving\Block\Pricing\Render\PriceBox</item>
                <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">Project_ProductPriceSaving::product/price/final_price.phtml</item>
                    </item>
                </item>
            </argument>
        </arguments>
    </referenceBlock>
</layout>

I also have a block at Block/Pricing/Render/PriceBox.php, which extends Magento\Framework\Pricing\Render\PriceBox and adds some extra methods, and my template exists at view/frontend/layout/templates/product/price/final_price.phtml.

I don't get any errors, but the final price for a simple product still renders using module-catalog/view/base/templates/product/price/final_price.phtml. As far as my understanding goes, Magento should be picking up my override, but I must be missing something.

Best Answer

Turns out the issue was the template path. It had been added in the layout folder, and should've been added in the following location:

view/frontend/templates/product/price/final_price.phtml.

Apart from that, the above code works fine.

Related Topic