Shopify Liquid:用if语句给当前门店链接加active类
Shopify跨门店导航链接动态高亮实现方案
核心实现逻辑
- 遍历渲染块前先通过
request.url识别当前访问的门店,将门店标识存为变量,避免循环内重复执行判断 - 渲染门店链接容器时,若容器对应门店和当前访问门店匹配,自动追加
active类 - 为
active类配置加粗、下划线样式,实现高亮效果
修改完成的Liquid代码
{% comment %} 提前识别当前门店,减少重复逻辑执行 {% endcomment %} {% assign current_store = '' %} {% if request.url contains 'source-bmx-testing.myshopify.com' %} {% assign current_store = 'bmx' %} {% elsif request.url contains 'sourceskate.myshopify.com' %} {% assign current_store = 'skate' %} {% endif %} {%- for block in section.blocks -%} {%- case block.type -%} {%- when 'bmx-link' -%} <a class="link-container" href="{{ block.settings.store_link }}"> <div class="bmx-store{% if current_store == 'bmx' %} active{% endif %}"> <img width="15" height="15" src="{{ block.settings.icon_image | img_url: '15x15' }}" srcset="{{ block.settings.icon_image | img_url: '15x15' }}" alt="{{ block.settings.icon_image.alt }}"> <span>{{ block.settings.store_link_title }}</span> </div> </a> {%- when 'skate-link' -%} <a class="link-container" href="{{ block.settings.store_link }}"> <div class="skate-store{% if current_store == 'skate' %} active{% endif %}"> <img width="15" height="15" src="{{ block.settings.icon_image | img_url: '15x15' }}" srcset="{{ block.settings.icon_image | img_url: '15x15' }}" alt="{{ block.settings.icon_image.alt }}"> <span>{{ block.settings.store_link_title }}</span> </div> </a> {%- endcase -%} {%- endfor -%}
配套CSS样式
将以下样式添加到主题全局样式文件中,即可实现要求的高亮效果:
.bmx-store.active, .skate-store.active { font-weight: 700; text-decoration: underline; }
优化说明
- 域名判断逻辑放在循环外,相比循环内重复判断执行效率更高
- 后续如果更换门店域名,仅需修改最上方的域名匹配规则,无需调整循环渲染逻辑
- 如果需要给外层
<a>标签也添加高亮状态,用相同的判断逻辑给a标签的class属性追加active类即可
内容的提问来源于stack exchange,提问作者user18791202
相关产品推荐
相关产品推荐

