如何获取Shopware 6中已选变体值的模板变量?
在Shopware 6模板中显示选中的变体值
要实现你想要的效果(选中变体后显示“属性名: 属性值”),可以在产品详情页的Twig模板中使用page.product.selectedVariation这个核心变量,下面是具体的实现方式:
基础实现(支持多属性变体)
如果你的产品有多个变体属性(比如颜色+尺寸),这段代码会遍历所有已选中的属性并逐个显示:
{% if page.product.selectedVariation %} {% for option in page.product.selectedVariation.options %} <div class="selected-variation-item"> {{ option.group.translated.name }}: {{ option.translated.name }} </div> {% endfor %} {% endif %}
单个属性的简化实现
如果你的产品只有单个变体属性(比如仅颜色),可以直接取第一个选中的选项:
{% if page.product.selectedVariation and page.product.selectedVariation.options is not empty %} {% set selectedOption = page.product.selectedVariation.options[0] %} <div class="selected-variation"> {{ selectedOption.group.translated.name }}: {{ selectedOption.translated.name }} </div> {% endif %}
变量说明
page.product.selectedVariation:存储当前用户选中的变体集合,未选中任何变体时为null,所以一定要加判断避免模板报错option.group.translated.name:变体属性组的多语言名称(比如你的“Color”)option.translated.name:选中的变体属性值的多语言名称(比如“Black”)
你可以把这段代码放在产品详情页的合适位置,比如产品标题下方、变体选择器附近,来展示选中的变体信息。
内容的提问来源于stack exchange,提问作者Datastorm1989
相关产品推荐
相关产品推荐

