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

Shopware 6插件:无法在商品详情页Twig访问ProductDetailRouteResponse扩展属性

解决Shopware 6模板无法访问扩展属性的问题

排查与修复步骤

1. 确认路由装饰器的注册与优先级

确保你的MyCustomProductDetailRoute已正确注册为原ProductDetailRoute的装饰器,且优先级足够高(数值越小优先级越高,保证你的逻辑在其他同类装饰器之前执行)。

服务注册示例(src/Resources/config/services.xml):

<service id="MyPlugin\Core\Content\Product\SalesChannel\MyCustomProductDetailRoute" decorates="Shopware\Core\Content\Product\SalesChannel\Detail\ProductDetailRoute">
    <argument type="service" id="MyPlugin\Core\Content\Product\SalesChannel\MyCustomProductDetailRoute.inner"/>
</service>

2. 保证在父类方法执行后添加扩展

你的路由类需继承原路由,先调用父类load方法获取原始响应,再添加扩展,避免修改被覆盖:

<?php

namespace MyPlugin\Core\Content\Product\SalesChannel;

use Shopware\Core\Content\Product\SalesChannel\Detail\ProductDetailRoute;
use Shopware\Core\Content\Product\SalesChannel\Detail\ProductDetailRouteResponse;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\HttpFoundation\Request;

class MyCustomProductDetailRoute extends ProductDetailRoute
{
    public function load(Request $request, SalesChannelContext $context, Criteria $criteria): ProductDetailRouteResponse
    {
        // 先执行父类逻辑获取页面实例
        $response = parent::load($request, $context, $criteria);
        $productPage = $response->getResult();

        // 将变量包装为Shopware Struct类型(必须是Struct子类)
        $expectedShippingCosts = new ArrayStruct([
            'amount' => 15.99, // 替换为你的实际计算值
            'currency' => $context->getCurrency()->getSymbol()
        ]);

        // 添加扩展到页面实例
        $productPage->addExtension('expectedShippingCosts', $expectedShippingCosts);

        return $response;
    }
}

3. 确保扩展变量为Shopware Struct类型

Shopware的扩展系统仅接受Shopware\Core\Framework\Struct\Struct的子类(如ArrayStruct、自定义Struct或实体类),普通标量、数组无法被正确存入extensions集合。

4. 清理缓存并验证

修改代码后执行缓存清理命令:

bin/console cache:clear

刷新页面后重新dump(page),确认extensions中已包含expectedShippingCosts。

5. 模板中正确访问属性

确认扩展存在后,在Twig模板中通过以下方式访问:

{# 访问扩展内的具体属性 #}
预计运费:{{ page.extensions.expectedShippingCosts.amount }} {{ page.extensions.expectedShippingCosts.currency }}

{# 查看扩展完整内容 #}
{% dump(page.extensions.expectedShippingCosts) %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:36:20