如何使用 html 选择元素的值对 Shopify 液体中的集合进行排序

How to use value of html select element to sort collection in Shopify liquid

本文关键字:集合 排序 html 何使用 选择 元素 Shopify      更新时间:2023-09-26

我有以下html选择元素:

<div class="sort-collection-by">
<label for="sort-by">Sort by</label> 
<select id="sort-by">
    <option value="manual">Featured</option>
    <option value="price-ascending">Price: Low to High</option>
    <option value="price-descending">Price: High to Low</option>
    <option value="title-ascending">A-Z</option>
    <option value="title-descending">Z-A</option>
    <option value="created-ascending">Oldest to Newest</option>
    <option value="created-descending">Newest to Oldest</option>
    <option value="best-selling">Best Selling</option>
</select>
</div>

我想在以下液体标签中使用所选选项,我已经指示SELECT_CHOICE_HERE。

{% assign sorted_products = collection.products | sort: SELECT_CHOICE_HERE %}
{% for product in sorted_products %}

我想在选择元素值更改时立即执行排序操作。

感谢您的任何帮助。

Funk Doc 关于遵循此的建议 Shopify 教程也是我推荐的。

此要点(来自上面的教程)显示了如何将事件处理程序绑定到sort-by下拉列表中的"change"事件,从而在下拉列表中的选定值更改时触发排序:

jQuery('#sort-by').bind('change', function() {
  Shopify.queryParams.sort_by = jQuery(this).val();
  location.search = jQuery.param(Shopify.queryParams).replace(/'+/g, '%20');
});

这需要在Javascript中完成的原因是因为Liquid是在服务器端渲染的,所以:

{% assign sorted_products = collection.products | sort: SELECT_CHOICE_HERE %}

。在用户有机会从下拉菜单中选择选项之前,已经呈现。这里需要Javascript来处理客户端的用户事件。