Twig变量判定异常排查(Shopware 6.5.6.1环境)
Shopware 6.5.6.1 Twig模板扩展属性判定异常问题
问题场景
在Shopware 6.5.6.1后台Twig模板中执行以下判定代码:
{% if item["extensions"]["my_plugin_extension"]["description"] is empty %} empty - {% else %} not empty - {% endif %} {% if item["extensions"]["my_plugin_extension"]["description"] is null %} null - {% else %} not null - {% endif %} {% if item["extensions"]["my_plugin_extension"]["description"] is defined %} defined - {% else %} not defined - {% endif %}
已知item["extensions"]的实际结构(JSON格式):
{ "my_plugin_extension": { "promotionId": "018d5b238e6479e88d0d341d943aae8e", "mediaId": "018b865c7b897028b477b618f44f446c", "description": "voopar", "createdAt": "2024-02-01T06:03:48.297+00:00", "updatedAt": "2024-02-01T06:04:08.544+00:00" } }
预期输出为 not empty - not null - defined,但实际输出为 empty - null - defined -。
异常原因
核心问题是模板中直接用多层数组下标访问的方式,没有正确解析Shopware的Extension实体对象:
- Shopware里的扩展字段(Extension)并不是普通的JSON对象,而是封装后的
Extension实体类实例,它实现了ArrayAccess接口,但仅支持第一层的数组下标访问(比如item["extensions"]["my_plugin_extension"]能拿到Extension对象)。 - 当你继续用
["description"]访问时,相当于把Extension对象当成普通数组去取description键,而这个键在对象的数组访问逻辑里不存在,所以返回null——这就导致empty和null判定为真,只有defined判定为真(因为你确实访问了这个键路径,只是对应值为null)。
正确访问方式
可以用以下两种方式正确获取扩展属性:
- 使用对象属性访问语法:
{% if item.extensions.my_plugin_extension.description is empty %} empty - {% else %} not empty - {% endif %}
或者动态键名场景下:
{% if item.extensions['my_plugin_extension'].description is empty %} empty - {% else %} not empty - {% endif %}
- 通过Shopware提供的
getExtension方法获取:
{% set myExtension = item.getExtension('my_plugin_extension') %} {% if myExtension.description is empty %} empty - {% else %} not empty - {% endif %}
内容的提问来源于stack exchange,提问作者Marc Cheng
相关产品推荐
相关产品推荐

