【问题标题】:How to paginate a sorted Jekyll collection?如何对已排序的 Jekyll 集合进行分页?
【发布时间】:2016-08-24 11:05:04
【问题描述】:

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

{% 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 解决方案是在文档文件名前加上数字,以确保它们默认的顺序正确。但是,当我移交网站时,这将不起作用,因为我无法信任非技术内容创建者来保持文件名有序。

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    您链接的技术几乎就是我在下一个/上一个集合中使用的技术。如果链接过时,这里有一个类似的 sn-p,它保存集合项目对象而不仅仅是 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,它确实有效!我认为诀窍在于捕获集合名称并将其作为字符串分配给变量。

      有没有人有更好/不那么冗长的方法?

      【讨论】:

        猜你喜欢
        • 2015-09-18
        • 2018-04-18
        • 2021-03-04
        • 1970-01-01
        • 2011-04-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多