在收藏页面,过滤器中的尺寸选项显示混乱,大致是这样的:
M-Size
XS-Size
L-Size
S-Size
我需要这样组织它:
XS-Size
S-Size
M-Size
L-Size
我有一个想法。我创建了一个具有这些大小的数组,但顺序正确。像这样:
{% assign sizes_order_array = 'XS-Size,S-Size,M-Size,L-Size' | upcase | split: "," %}
我只想在
if
循环内映射 for
条件中的每个选项。事情是这样的:
{% for filter in collection.filters %}
<ul>
{% for filter_value in filter.values %}
{% capture option_item %}
<li>...any option size code</li>
{% endcapture %}
{% assign filter_value_label = filter_value.label | upcase %}
{% for size in sizes_order_array %}
{% if filter_value_label == size %}
{{ option_item }}
{% endif %}
{% endfor %}
{% endfor %}
</ul>
{% endfor %}
我将
li
标签本身和选项主体放在 capture
中。并且此代码仍然以与以下相同的顺序显示选项:
M-Size
XS-Size
L-Size
S-Size
为什么会出现这种情况?我正在做
{% if filter_value_label == size %} ... {% endif %}
检查。
有什么错误,请告诉我!
问题在于如何构造 option_item 变量。您正在捕获 HTML
<li>
标记本身,但循环内的条件检查不会控制最终输出中项目的顺序。相反,它仅决定是否显示每个 <li>
标签。
要根据 size_order_array 对选项重新排序,您需要在输出之前以正确的顺序构造整个
<li>
元素列表。以下是实现这一目标的方法:
{% assign sizes_order_array = 'XS-Size,S-Size,M-Size,L-Size' | upcase | split: "," %}
{% for filter in collection.filters %}
<ul>
{% assign sorted_options = '' %}
{% for filter_value in filter.values %}
{% assign filter_value_label = filter_value.label | upcase %}
{% if sizes_order_array contains filter_value_label %}
{% capture option_item %}
<li>{{ filter_value_label }}</li>
{% endcapture %}
{% assign sorted_options = sorted_options | append: option_item %}
{% endif %}
{% endfor %}
{{ sorted_options }}
</ul>
{% endfor %}
此代码迭代每个过滤器值并检查其标签是否与sizes_order_array 中的任何尺寸匹配。如果是,它会构造
<li>
元素并将其附加到 Sorted_options 变量中。最后,它输出sorted_options,其中包含按正确顺序排列的所有<li>
元素。