shopify现在大部分主题都已经启用了官方的搜索插件“Search & Discovery”,但是官方的筛选插件在tag筛选方面做的不够灵活。在部分情况下我们要使用tag实现更加灵活的筛选(如下图所示)。
如何实现呢。(以下所有代码都不含html与css,需要自己美化)
贴出筛选的代码
{% comment %}输出选择后的tag{% endcomment %}
{% if current_tags.size > 0 %}
<div class="filtered-tags flex flex-wrap items-center{% if animated %} sf-scroll-trigger animate--{{ animation_effect }}{% endif %}">
<ul id="sf-filter-by-items" class="flex flex-wrap">
{%- for tag in current_tags -%}
<li class="filtered-item" data-tag-filter>
<span class="mr-2">
<svg class="w-[16px] h-[16px]" fill="currentColor" stroke="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512">
<path d="M193.94 256L296.5 153.44l21.15-21.15c3.12-3.12 3.12-8.19 0-11.31l-22.63-22.63c-3.12-3.12-8.19-3.12-11.31 0L160 222.06 36.29 98.34c-3.12-3.12-8.19-3.12-11.31 0L2.34 120.97c-3.12 3.12-3.12 8.19 0 11.31L126.06 256 2.34 379.71c-3.12 3.12-3.12 8.19 0 11.31l22.63 22.63c3.12 3.12 8.19 3.12 11.31 0L160 289.94 262.56 392.5l21.15 21.15c3.12 3.12 8.19 3.12 11.31 0l22.63-22.63c3.12-3.12 3.12-8.19 0-11.31L193.94 256z"/>
</svg>
</span>
{{- tag | link_to_remove_tag: tag -}}
</li>
{%- endfor -%}
<li class="text-color-secondary font-normal underline hover:text-color-primary px-3 py-1.5" data-tag-filter>
<a
aria-label="{{ 'collections.sidebar.clear_all' | t }}"
href="{{ collection.url }}?sort_by={{ collection.sort_by }}"
>
Clear all
</a>
</li>
</ul>
</div>
{% endif %}
{% comment %}输出选择后的tag{% endcomment %}
{% comment %}获取分类所有的tag{% endcomment %}
{% if collection.all_tags.size > 0 %}
<ul class="tag-filters">
{% for tag in collection.all_tags %}
{% if current_tags contains tag %}
<li class="tag-filters__item active">{{ tag | link_to_remove_tag: tag }}</li>
{% else %}
<li class="tag-filters__item">{{ tag | link_to_add_tag: tag }}</li>
{% endif %}
{% endfor %}
</ul>
{% endif %}
{% comment %}获取分类所有的tag{% endcomment %}
最后实现的效果如下图(自驾加上必要的css美化即可)
我们还可以在主题自定义加入特定的条件,输出特定的tag(如下图所示)
代码如下
//在schema配置区域加入新的blocks模块,代码如下
"blocks": [
{
"type": "filter",
"name": "Tag filter",
"limit": 50,
"settings": [
{
"type": "text",
"id": "filter_name",
"label": "Title"
},
{
"type": "textarea",
"id": "filter_tags",
"label": "Filter tags",
"info": "Add a comma-separated list of product tags. Only the tags found in the collection will be displayed as filters. [Learn more](https://help.outofthesandbox.com/hc/en-us/articles/115008642047)"
}
]
}
]
//页面里面的代码,判断设置的tag是否在当前分类下有,有的话则输出tag
{% comment %}输出特定条件的tag{% endcomment %}
{% for block in section.blocks %}
{%- case block.type -%}
{%- when 'filter' -%}
<h1>{{ block.settings.filter_name | escape }}</h1>
{% assign filter_tags = block.settings.filter_tags | split:"," %}
{% for tag in filter_tags %}
{%- for all_tags in collection.all_tags -%}
{% if tag == all_tags %}
{{ tag }}
{% endif %}
{% endfor %}
{% endfor %}
{% endcase %}
{% endfor %}
{% comment %}输出特定条件的tag{% endcomment %}