Skip to content

Instantly share code, notes, and snippets.

@Phlow
Last active April 30, 2024 13:30
Show Gist options
  • Save Phlow/1f27dfafdf2bbcc5c48e to your computer and use it in GitHub Desktop.
Save Phlow/1f27dfafdf2bbcc5c48e to your computer and use it in GitHub Desktop.
This Liquid loop for Jekyll sorts a collection by date in reverse order
{% comment %}
*
* This loop loops through a collection called `collection_name`
* and sorts it by the front matter variable `date` and than filters
* the collection with `reverse` in reverse order
*
* To make it work you first have to assign the data to a new string
* called `sorted`.
*
{% endcomment %}
<ul>
{% assign sorted = site.collection_name | sort: 'date' | reverse %}
{% for item in sorted %}
<li>{{ item.title }}</li>
{% endfor %}
</ul>
@Phlow
Copy link
Author

Phlow commented May 11, 2021

@minheeyoon You‘re welcome. 😸

@wdzajicek
Copy link

The date key is now default

As of Jekyll > v4.0.0 date, is the default key used for sorting collection items (provided the collection items have date keys.) The original liquid variable-assignment can be shortened:

<!-- `| sort: 'date '` can be omitted -->
{% assign sorted = site.collection_name | sort: 'date' | reverse %}
<!-- This will accomplish the same thing  -->
{% assign sorted = site.collection_name | reverse %}

By default, two documents in a collection are sorted by their date attribute when both of them have the date
key in their front matter. However, if either or both documents do not have the date key in their front matter,
they are sorted by their respective paths.
https://jekyllrb.com/docs/collections/#custom-sorting-of-documents

See Custom Sorting of Documents on the Collections page of Jekyll docs for more info.

@Phlow
Copy link
Author

Phlow commented Sep 3, 2021

I haven't tested your suggestion. But you write provided the collection items have date keys.

I think for being save it doesn't hurt, in case no date is associated, it doesnt count. What do you think?

@prabhav
Copy link

prabhav commented Oct 11, 2021

Thanks so much for sharing this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment