You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Magento 2中覆写可配置产品列表页的价格HTML?

解决Magento 2列表页可配置产品价格HTML覆写问题

问题原因

列表页中,可配置产品的价格渲染使用的是Magento\ConfigurableProduct\Pricing\Render\FinalPriceBox类,而非你当前覆写的Magento\Catalog\Pricing\Render\FinalPriceBox,因此自定义逻辑仅对简单产品生效。

解决方案

1. 修正自定义类语法错误

你的Callforprice.php文件中类注释缺少起始标记/**,会导致语法错误,先修正:

namespace Vendor\MyModule\Block;

/**
 * Product price block
 */
class Callforprice extends \Magento\Catalog\Pricing\Render\FinalPriceBox 
{
    /**
     * Wrap with standard required container
     *
     * @param string $html
     * @return string
     */
    protected function wrapResult($html)
    {
        return '-TEST-<div class="price-box ' . $this->getData('css_classes') . '" ' .
            'data-role="priceBox" ' .
            'data-product-id="' . $this->getSaleableItem()->getId() . '" ' .
            'data-price-box="product-id-' . $this->getSaleableItem()->getId() . '"' .
            '>' . $html . '</div>';
    }
}

2. 扩展DI配置,覆写可配置产品价格渲染类

修改app\code\Vendor\MyModule\etc\di.xml,新增可配置产品FinalPriceBox的偏好设置:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <!-- 覆写简单产品价格渲染 -->
    <preference for="Magento\Catalog\Pricing\Render\FinalPriceBox" type="Vendor\MyModule\Block\Callforprice" />
    <!-- 覆写可配置产品价格渲染 -->
    <preference for="Magento\ConfigurableProduct\Pricing\Render\FinalPriceBox" type="Vendor\MyModule\Block\ConfigurableCallforprice" />
</config>

3. 创建可配置产品自定义价格渲染类

在app\code\Vendor\MyModule\Block目录下新建ConfigurableCallforprice.php,可选择两种实现方式:

方式一:直接继承可配置产品原类并实现逻辑
namespace Vendor\MyModule\Block;

use Magento\ConfigurableProduct\Pricing\Render\FinalPriceBox as ConfigurableFinalPriceBox;

/**
 * Configurable product price block
 */
class ConfigurableCallforprice extends ConfigurableFinalPriceBox
{
    /**
     * Wrap with standard required container
     *
     * @param string $html
     * @return string
     */
    protected function wrapResult($html)
    {
        return '-TEST-<div class="price-box ' . $this->getData('css_classes') . '" ' .
            'data-role="priceBox" ' .
            'data-product-id="' . $this->getSaleableItem()->getId() . '" ' .
            'data-price-box="product-id-' . $this->getSaleableItem()->getId() . '"' .
            '>' . $html . '</div>';
    }
}
方式二:继承自定义的Callforprice类复用逻辑(避免代码重复)
namespace Vendor\MyModule\Block;

/**
 * Configurable product price block
 */
class ConfigurableCallforprice extends Callforprice
{
    // 无需重写方法,直接复用父类的wrapResult逻辑
}

4. 清理缓存并测试

执行命令清理缓存后刷新列表页:

bin/magento cache:clean
bin/magento cache:flush

内容的提问来源于stack exchange,提问作者MarioProject

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:41:12