Shopify Impulse主题中自动隐藏空合集的实现求助
在Shopify Impulse主题中自动隐藏空合集的解决方案
你可以通过以下修改实现自动隐藏空合集,核心是先获取导航链接对应的合集对象,再判断产品数量是否大于0:
修改后的代码
{%- for grandchildlink in childlink.links -%} {%- assign target_collection = collections[grandchildlink.handle] -%} {%- if target_collection and target_collection.products.size > 0 -%} <div> <a href="{{ grandchildlink.url }}" class="site-nav__dropdown-link"> {{ grandchildlink.title }} </a> </div> {%- endif -%} {%- endfor -%}
代码说明
{%- assign target_collection = collections[grandchildlink.handle] -%}:通过导航链接的handle匹配到对应的合集对象。Shopify导航中合集链接的handle和合集本身的handle完全一致,因此可以用这种方式获取合集数据。{%- if target_collection and target_collection.products.size > 0 -%}:先判断合集是否存在(避免无效链接报错),再判断合集内的产品数量是否大于0,只有同时满足两个条件才渲染该导航链接。
补充:如果导航包含非合集链接
如果你的导航里还有页面、产品等其他类型的链接,不想过滤它们,可以用下面的代码,只针对合集链接做隐藏处理:
{%- for grandchildlink in childlink.links -%} {%- if grandchildlink.type == 'collection' -%} {%- assign target_collection = collections[grandchildlink.handle] -%} {%- if target_collection and target_collection.products.size > 0 -%} <div> <a href="{{ grandchildlink.url }}" class="site-nav__dropdown-link"> {{ grandchildlink.title }} </a> </div> {%- endif -%} {%- else -%} <!-- 非合集类型的链接正常显示 --> <div> <a href="{{ grandchildlink.url }}" class="site-nav__dropdown-link"> {{ grandchildlink.title }} </a> </div> {%- endif -%} {%- endfor -%}
内容的提问来源于stack exchange,提问作者Harry
相关产品推荐
相关产品推荐

