首页 文章

如何对已排序的Jekyll集合进行分页?

提问于
浏览
0

我正在尝试创建导航到集合中上一页/下一页的左/右箭头链接 . 这对于标准集合来说很容易实现:

{% if page.previous %}
  <a href="{{ page.previous.url }}>Left arrow</a>
{% endif %}
{% if page.next %}
  <a href="{{ page.next.url }}>Right arrow</a>
{% endif %}

我遇到的问题是,这只是按文件顺序循环收集 . 我需要使用frontmatter变量( position )为页面指定特定顺序 .

我搜索的范围很广,但所有与排序有关的信息似乎都适用于网站导航而不是分页 . 在将已排序的集合分配给变量之后,我似乎需要使用液体循环 . 我正努力让 page.previouspage.next 变量在这个循环中运行 .

我试图遍历已排序集合中的文档,并仅在文档URL与当前页面匹配时输出导航箭头,但这似乎不起作用:

{% assign sorted_collection site.collection | sort: "position" %}

{% for document in sorted_collection %}

  {% if document.url == page.url %}

    {% if document.previous %}
      <a href="{{ document.previous.url }}>Left arrow</a>
    {% endif %}

    {% if document.next %}
      <a href="{{ document.next.url }}>Right arrow</a>
    {% endif %}

  {% endif %}

{% endfor %}

我的液体语法中是否遗漏了某些内容,或者我的逻辑在这里完全走错了路线?

我目前的hacky解决方案是在文档文件名前加上数字,以确保默认情况下它们的顺序正确 . 但是当我将网站交给我时,这将无法工作,因为我无法信任非技术内容创建者并保持文件名的顺序 .

2 回答

  • 0

    您链接的技术几乎就是我用于下一个/上一个集合的技术 . 如果链接过时,这里有一个类似的片段保存集合项对象而不仅仅是URL:

    {% if page.collection %}
      {% assign collection = site[page.collection] | sort: 'position' %}
      {% assign prev = collection | last %}
      {% assign next = collection | first %}
    
      {% for item in collection %}
        {% if item.title == page.title %}
          {% unless forloop.first %}
            {% assign prev = iterator %}
          {% endunless %}
    
          {% unless forloop.last %}
            {% assign next = collection[forloop.index] %}
          {% endunless %}
        {% endif %}
    
        {% assign iterator = item %}
      {% endfor %}
    {% endif %}
    
    {% if prev %}
      <a href="{{ prev.url }}">{{ prev.title }}</a>
    {% endif %}
    
    {% if next %}
      <a href="{{ next.url }}">{{ next.title }}</a>
    {% endif %}
    
  • 2

    我刚刚找到并测试了解决方案suggested here并且它有效!我认为诀窍在于捕获集合名称并将其作为字符串分配给变量 .

    有没有人有更好/更简洁的方式这样做?

相关问题