侧边栏进入活跃分类最深层级时如何显示同级分类?
实现侧边栏分类导航:最深层级显示同级分类
需求:进入分类的最深层级(该分类无下级子分类)时,侧边栏应显示其同级分类。
修改后的Twig代码如下:
{% block layout_navigation_categories_list_entry %} {% set isDeepestLevel = activeResult.children is empty %} {% set isCurrentCategory = item.category.id in activeResult.id %} {% set isSiblingCategory = isDeepestLevel and item.category.parentId == activeResult.parentId %} {# 递归加载子分类(仅当前分类在活跃路径中时) #} {% if item.category.id in activeResult.path %} {% block layout_navigation_categories_recoursion %} {% set levelIncrement = isCurrentCategory ? 1 : 0 %} {% sw_include '@Storefront/storefront/layout/sidebar/category-navigation.html.twig' with { navigationTree: item.children, activeResult: activeResult, level: level + levelIncrement } only %} {% endblock %} {% endif %} {# 显示当前分类、父分类,或最深层级时的同级分类 #} {% if isCurrentCategory or item.category.parentId in activeResult.id or (isDeepestLevel and isSiblingCategory) %} {{ parent() }} {% endif %} {% endblock %}
关键逻辑说明:
isDeepestLevel:判断当前活跃分类是否为最深层级(无下级子分类)isSiblingCategory:判断当前遍历的分类是否是活跃分类的同级(父ID相同)- 最后显示条件新增了
(isDeepestLevel and isSiblingCategory),当处于最深层级时,同级分类会被渲染出来 - 保留了原有的递归逻辑,确保非最深层级时的正常展开行为
内容的提问来源于stack exchange,提问作者Joshi
相关产品推荐
相关产品推荐

