Jekyll: don't sort the collection by date

It makes me crazy.

I have this resources collection:

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

All have dates:

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

Pages are generated, and if I try to display the date, it displays correctly, but I also want to sort them 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 use:

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

thanks

+6
source share
3 answers

I am currently experiencing the same issue with collections.

When I try to sort by European formatted dates, for example dd/mm/yyyy or dd-mm-yyyy , I get a string sort. Even when timezone: Europe/Paris installed in the _config.yml file.

The only way to get sorted by date is to use the ISO format yyyy-mm-dd .

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

And sorting now works.

Change Here's how jekyll manages the "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 

If you do not need Time, you can adhere to the format date: YYYY-MM-DD . And you must be consistent in your collection. If you mix String, Date and / or Time Liquid will give an error, for example Liquid error: comparison of Date with Time failed or Liquid error: comparison of String with Date failed

+3
source

If your collection items have a valid date ( ISO 8601 format ), then in the first case they will be sorted by date automatically, the oldest of them.

If you want to output more recent elements, you can reverse order as follows:

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

I got: resources sorted by date string (e.g. 19-06-2015 ), which was incorrect.

Instead, I created my own filter:

 # _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 this:

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

Source: https://habr.com/ru/post/989387/


All Articles