Shopify中如何为分页URL追加ID?实现博客评论锚点跳转
Got it, let's tackle this problem. You want to append an anchor ID to your pagination URLs so that when users click a pagination button, the page automatically scrolls straight to your blog's comments section. Here are two reliable ways to adjust your Liquid code:
Method 1: Modify the Existing default_pagination Output (Regex Approach)
If you want to stick with using the default_pagination filter, you can add an extra regex-based replacement to append the anchor to every pagination link's URL. This works on platforms that support Liquid's replace_regex filter (like Shopify, Jekyll 3+, etc.):
{{ paginate | default_pagination: previous: previous_label, next: next_label | replace: 'view=ajax', '' | replace_regex: /href="([^"]+)"/, 'href="$1#comments"' }}
Breakdown:
- We keep your original
replace: 'view=ajax', ''to remove the AJAX view parameter. - The new
replace_regexfilter targets everyhref="..."attribute in the generated pagination HTML. ([^"]+)captures the full URL inside the quotes, then we append#comments(replace this with your actual comments section ID, e.g.,#comment-section) to the end of the captured URL.
Method 2: Manually Build Pagination Links (More Compatible)
If your Liquid environment doesn't support replace_regex, or you prefer more control over the output, skip the default_pagination filter and build the links manually. This approach is universally compatible across all Liquid implementations:
{% if paginate.previous %} <a href="{{ paginate.previous.url }}#comments">{{ previous_label }}</a> {% endif %} {% for part in paginate.parts %} {% if part.is_link %} <a href="{{ part.url }}#comments">{{ part.title }}</a> {% else %} <span>{{ part.title }}</span> {% endif %} {% endfor %} {% if paginate.next %} <a href="{{ paginate.next.url }}#comments">{{ next_label }}</a> {% endif %}
Breakdown:
- We directly append
#commentsto each pagination URL (paginate.previous.url,part.url,paginate.next.url). - This gives you full control over the HTML structure of your pagination, and ensures the anchor is added reliably every time.
- Again, swap
#commentswith the actual ID of your comments container element.
Either method will make sure that when a user clicks a pagination button, the page loads and automatically scrolls to the section with the matching ID.
内容的提问来源于stack exchange,提问作者Jason Biondo

