Shopify中高亮当前活动集合按钮问题求助
解决Shopify集合列表按钮高亮无效的问题
嘿,我一眼就看出你代码里的问题啦!你用的link.active标签在这里根本起不了作用,原因很简单:这个标签是专门给通过linklists调用的导航菜单链接项用的,而你现在是直接遍历collections集合,当前循环上下文里根本没有link这个对象,自然取不到link.active的值~
另外还要提一句,你原来代码里{% if link.active %}class='active'{% endif %}的写法也有问题,就算条件生效,也会生成重复的class属性(比如变成class="btn btn-outline-info class='active'"),这是不符合HTML规范的,正确的做法是直接把active作为类名加进去就行。
下面给你两种靠谱的修正方案:
方案一:用current_collection对象判断(推荐)
Shopify提供了current_collection全局对象,它会自动指向当前访问的集合页面对应的集合实例。我们可以通过对比集合的handle(每个集合的handle都是唯一的,比URL更可靠)来判断是否为当前集合:
{% for collection in collections %} {% unless collection.handle == 'frontpage' %} <button type="button" class="btn btn-outline-info {% if collection.handle == current_collection.handle %}active{% endif %}"> {{ collection.title | escape | link_to: collection.url }} </button> {% endunless %} {% endfor %}
方案二:对比当前页面路径和集合URL
如果你更习惯用URL来判断,也可以对比request.path(当前页面的路径)和集合的url:
{% for collection in collections %} {% unless collection.handle == 'frontpage' %} <button type="button" class="btn btn-outline-info {% if collection.url == request.path %}active{% endif %}"> {{ collection.title | escape | link_to: collection.url }} </button> {% endunless %} {% endfor %}
不过这种方法要注意,当URL带有额外参数(比如排序参数)时,request.path会和collection.url不一致,所以还是方案一更稳妥。
内容的提问来源于stack exchange,提问作者xtremeCODE
相关产品推荐
相关产品推荐

