杰基尔:无法按日期对收集进行排序

时间:2015-06-19 08:43:08

标签: jekyll

这让我很疯狂。

我有这个集合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

由于

3 个答案:

答案 0 :(得分:6)

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

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

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

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

现在这种情况正在发挥作用。

修改 - 这就是jekyll管理&#39; date&#39;:

的方式
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格式。 而且你必须在整个系列中保持一致。如果混合字符串,日期和/或时间液体将引发错误,如Liquid error: comparison of Date with Time failedLiquid error: comparison of String with Date failed

答案 1 :(得分:6)

如果您的收藏品在前面的内容中有有效的dateISO 8601 format),则会自动按日期排序,最早排序。

如果您想首先输出更多近期商品,可以reverse订购此类订单:

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

答案 2 :(得分:2)

我得到了:按日期字符串排序的资源(例如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 %}
相关问题