Jekyll:无法按日期排序 collection

Jekyll: can't sort collection by date

这让我发疯。

我有这个 collection resources:

# _config.yml
collections:
  resources:
    output: true
    permalink: /resources/:name/

他们都有日期:

# /_resources/example.md
---
title: Learn the Web
date: 09-04-2013  
---

页面已生成,如果我尝试显示它的日期,它会正确显示,但我还想按日期对这些页面进行排序,但它不起作用。我做错了什么?

{% assign sortedResources = site.resources | sort: 'date' %} <!-- Doesn't work -->
{% for resource in sortedResources %}
  <div>
    {{resource.title}}
    <small>{{resource.date | date: "%d %b %Y"}}</small> <!-- Works -->
  </div>
{% endfor %}

我正在使用:

▶ ruby --version
ruby 2.1.4p265 (2014-10-27 revision 48166) [x86_64-linux]
▶ jekyll --version
jekyll 2.5.3

谢谢

我明白了:按日期字符串(例如 19-06-2015)排序的资源不正确。

我改为创建自定义过滤器:

# _plugins/filters.rb
module Jekyll
  module DateFilter
    require 'date'
    def date_sort(collection)
      collection.sort_by do |el|
        Date.parse(el.data['date'], '%d-%m-%Y')
      end
    end
  end
end
Liquid::Template.register_filter(Jekyll::DateFilter)

这样使用:

{% assign sortedResources = site.resources | date_sort | reverse %}
{% for resource in sortedResources %}
  <div>{{resource.title}}</div>
{% endfor %}

我目前遇到了与 collections 相同的问题。

在尝试对 dd/mm/yyyydd-mm-yyyy 等欧洲格式的日期进行排序时,我得到了字符串排序。即使在 _config.yml 文件中设置了 timezone: Europe/Paris

获得 collection 按日期排序的唯一方法是使用 ISO 格式 yyyy-mm-dd

# /_resources/example.md
---
title: Learn the Web
date: 2013-04-09  
---

现在排序正常了。

Edit - 这就是 jekyll 管理的方式 'dates':

date: "2015-12-21" # String
date: 2015-12-1    # String D not zero paded
date: 01-12-2015   # String French format
date: 2015-12-01   # Date
date: 2015-12-21 12:21:22  # Time
date: 2015-12-21 12:21:22 +0100 # Time

如果不需要时间,可以坚持使用 date: YYYY-MM-DD 格式。 而且你必须在 collection 中保持一致。如果您混合使用 String、Date and/or Time Liquid 将抛出类似 Liquid error: comparison of Date with Time failedLiquid error: comparison of String with Date failed

的错误

如果您的 Collection 项目在封面中有一个有效的 date (ISO 8601 format),它们将自动按日期排序,最早的在前。

如果您想先输出最近的项目,您可以reverse这样的顺序:

{% assign sorted = site.resources | reverse %}
{% for item in sorted %}
  <h1>{{ item.name }}</h1>
  <p>{{ item.content }}</p>
{% endfor %}