Shopware 6遍历面包屑数组取键为空,无法读取一级导航描述问题
Shopware 6 导航菜单描述空值问题解决
空值产生原因
page.header.navigation.active.breadcrumb的键默认是分类ID字符串,和page.header.navigation.tree的索引键并不保证完全匹配,导航树裁剪、非分类页场景下都会出现对应索引不存在的情况- Shopware 6 导航树默认加载逻辑不会预加载分类的
description字段,未扩展字段配置的前提下就算索引匹配也无法取到对应值 - 取值前未做存在性判断,会导致索引不存在时直接返回空值
修正后的模板代码
{% sw_extends "@Storefront/storefront/section/cms-section-sidebar.html.twig" %} {% set topMenu = null %} {% set topMenuDescription = '' %} {% for key, value in page.header.navigation.active.breadcrumb %} {# 面包屑索引从0开始,取第二层导航调整为loop.index0 == 1更稳妥 #} {% if loop.index0 == 1 %} {% set topMenu = value %} {# 先判断对应索引和分类对象存在再取值 #} {% if page.header.navigation.tree[key] is defined and page.header.navigation.tree[key].category is defined %} {% set topMenuDescription = page.header.navigation.tree[key].category.description %} {% endif %} {% endif %} {% endfor %} {% set currentMenu = page.header.navigation.active.breadcrumb | last %} {% block section_main_content_block %} <div class="category-top"> <div class="category-banner"> <img src="/media/6a/fd/8b/1632946677/listing-banner.jpg" alt="分类横幅"> <div class="category-banner-headlines"> {% if currentMenu != topMenu %} <h3>{{ topMenu }}</h3> <h2>{{ currentMenu }}</h2> {% else %} <h2 class="sameMenu">{{ currentMenu }}</h2> {% endif %} </div> </div> <div class="category-description"> <h1>{{ currentMenu }}</h1> {{ topMenuDescription | trans | raw }} </div> </div> {{ parent() }} {% endblock %}
扩展导航树字段(修改模板后仍取不到值时操作)
你需要在自定义主题或插件中扩展导航加载的字段配置,将description加入分类加载字段列表,最简实现方式如下:
- 在你的自定义主题
src/Resources/config/packages/shopware.yaml中添加如下配置:
shopware: storefront: navigation: category: additional_fields: ['description']
- 清理缓存后重新加载页面即可生效
内容的提问来源于stack exchange,提问作者Grimclaw Draven
相关产品推荐
相关产品推荐

