Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jekyll: can't sort collection by date

Tags:

jekyll

This is making me crazy.

I have this collection resources:

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

They all have dates:

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

The pages get generated, and if I try to display it's date, it is displayed correctly, but I also want to sort those by date, and it just doesn't work. What am I doing wrong?

{% 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 %}

I'm using:

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

Thanks

like image 288
Augustin Riedinger Avatar asked Jun 19 '15 08:06

Augustin Riedinger


1 Answers

I got it: the resources where sorted by the date string (eg. 19-06-2015) which was not correct.

I created my custom filter instead:

# _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)

Used like so:

{% assign sortedResources = site.resources | date_sort | reverse %}
{% for resource in sortedResources %}
  <div>{{resource.title}}</div>
{% endfor %}
like image 144
Augustin Riedinger Avatar answered Sep 23 '22 13:09

Augustin Riedinger