Shopify集合排序功能失效,Slate主题下官方推荐代码无法使用求助
If you've tried using Shopify's official recommended code for building a "Sort By" dropdown on collection pages and found it broken while developing with Shopify Slate, you're not alone. The original code often doesn't play nice with Slate's modern JavaScript environment and build pipeline—but there's a cleaner, adapted solution from the community that works perfectly.
The Adapted Working Code
First, here's the complete, Slate-friendly JavaScript to handle the dropdown change event:
document.addEventListener('DOMContentLoaded', function() { const sortDropdown = document.querySelector('#sort-by'); // Only run if the dropdown exists on the page if (sortDropdown) { sortDropdown.addEventListener('change', function() { const urlParams = new URLSearchParams(window.location.search); urlParams.set(this.name, this.value); window.location.search = urlParams.toString(); }); } });
Pair It With the Right Liquid HTML
You'll need to make sure your collection template has the corresponding dropdown markup. Add this to your collection page Liquid file (e.g., templates/collection.liquid or a section included in it):
<select id="sort-by" name="sort_by"> {% for option in collection.sort_options %} <option value="{{ option.value }}" {% if collection.current_sort == option.value %}selected{% endif %}> {{ option.name }} </option> {% endfor %} </select>
Why This Works Better Than the Original
- Modern API Usage: It leverages
URLSearchParamsinstead of messy string manipulation to handle URL parameters, which is more reliable and less error-prone in modern browsers. - DOM Safety: Wrapped in
DOMContentLoadedand checks for the dropdown element's existence first, preventing errors if the code runs on pages where the dropdown isn't present. - Slate Compatibility: This code fits seamlessly into Slate's modular JS structure—you can drop it into a template-specific JS file (like
assets/js/templates/collection.js) or your global JS file without conflicts.
Quick Setup Tips
- Double-check that the dropdown's
idmatches the selector in the JS (#sort-by)—adjust both if you use a different ID in your markup. - If you're using Slate's ES6 modules, you can export this function and import it where needed, but the vanilla JS version above works out of the box.
内容的提问来源于stack exchange,提问作者user4889134

