Custom comparator for sorting arrays in Liquid or Jekyll

133 views Asked by At

I am trying to set up a blog in Jekyll. Some (not all) of my posts have updated_on variable in its front matter which I use to store the date (YYYY-MM-DD HH:MM:SS +0530) it was last updated on.

I wish to display the posts on my index page in the decreasing order of post.updated_on if available, otherwise using post.date. To make things clear, here is pseudo-code of what I want my sort comparator to work like

comp(post a, post b){
    if(a.updated_on) t1 = a.updated_on
    else t1 = a.date

    if(b.updated_on) t2 = b.updated_on
    else t2 = b.date

    return t1>t2
}

How can I achieve this kind of sorting in Liquid/Jekyll?

One fallback I have thought is to add updated_on in every post even if it was never updated since post date. Then I could do something like

{% assign sorted_posts = paginator.posts | sort: 'updated_on' | reverse %}
{% for post in sorted_posts %}
  ... some code here ...
{% endfor %}

But I don't want to go this way since I will have to manually add updated_on to each post where it doesn't already exists.

0

There are 0 answers