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

Shopware升级后如何在Twig模板中正确遍历ArrayEntity

Shopware Twig模板遍历ArrayEntity方案

问题复现

后端添加扩展代码:

$event->getPage()->addExtension('downloads', new ArrayEntity($downloads));

Twig中执行{{ dump(page.extensions.downloads) }}可正常打印ArrayEntity实体对象。
版本更新前可用的遍历写法:

{% for key, files in page.extensions.downloads.data %}

版本更新后上述写法失效,data属性返回null;尝试直接遍历ArrayEntity对象本身:

{% for key, files in page.extensions.downloads %}

同样无法正常读取数据。

失效原因

Shopware版本迭代后,ArrayEntity内部存储数据的$data属性调整为受保护属性,不再支持直接通过公共属性读取,因此.data访问会返回null。同时Twig默认遍历逻辑不会自动适配ArrayEntity实现的迭代接口,直接遍历对象无法拿到存储的元素集合。

正确写法

使用ArrayEntity提供的公共方法获取存储的数据再遍历,全版本兼容性最好的写法是调用all()方法获取完整数据数组:

{% for key, files in page.extensions.downloads.all() %}
    {# 循环内部业务逻辑 #}
{% endfor %}

针对新版本也可以使用getIterator()方法获取迭代器遍历:

{% for key, files in page.extensions.downloads.getIterator() %}
    {# 循环内部业务逻辑 #}
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 08:31:21