0

I'm writing a site in Jekyll, which uses Liquid.

I have ymal for pages , like this:

---
title: Mytitle
posted: 2020-06-29
updated: 2020-07-29
....
---

And I have some posts, as follows

{
title: title1
posted: 2020-06-29
updated: 2020-07-29
},
{
title: title2
posted: 2020-07-05
},
{
title: title 3
posted: 2020-07-01
updated: 2020-07-20
},
{
title: title 4
posted: 2020-07-22
},

I expect the order of posts which is sorted by the latest date, i.e. latest(posted, updated).

liquid seems cannot sort by custom function? Can someone tell me what to do?

Thanks

Cynthia
  • 96
  • 7

1 Answers1

2

By default site.posts are sorted by the date property (newest fist), which you called posed. So you may want to rename it to date to make your life easier.

For custom sorting you can use the Liquid sort filter, which takes one argument.

So if you want to sort by updated instead, you can do that with:

{% assign my_sorted_list = site.posts | sort:"updated" %}
{% for post in my_sorted_list %}
  ...
{% endfor %}

You'll need to set the updated property then for every post or use a custom hook as explained here.

  • Thank you Jens . Before posting the question, I tried sort by `updated`. However the result did not meet my expectations. In my case, I expect get `title1 -> title4 -> title3 -> title2` , but got `title1 -> title3 -> title4 -> title2`. I kown I can add `updated` whitch value is same as `posted` in `title4` and `title2` to fix this question. But I am interested in that can liquid sort by a custom compare function,, like a function like [python](https://stackoverflow.com/questions/63149457/changing-a-variablestring-in-a-class-in-python/63149652#63149652)? – Cynthia Jul 31 '20 at 08:12
  • No, liquid doesn't provide such a function. Would be nice though. – Jens Krause Jul 31 '20 at 10:25