Jekyll Sorting as a string, should be a date

302 Views Asked by At

I am using Jekyll in conjunction with Prose and have set up an extra bit of meta data called pub_date.

In prose this is set up as a text field (datetime fields are not yet supported)

The user enters something like 2015-01-23 for pub_date, I can take this value and run it through the date method to output the date correctly (for example {{ post.pub_date | date: "%b %-d, %Y"}} works)

When I attempt to do a sort these values however they are treated as a string;

{% assign sorted_posts = (paginator.posts | sort: 'pub_date', 'first') %}

Is there a better way I should be sorting this collection? Or is there anything I can do to force the value to act like a date?

I am using github pages to host the solution, so we can't do anything custom with Jekyll unfortunately.

2

There are 2 best solutions below

0
David Rice On BEST ANSWER

I got errors when using a quoted string as the argument to sort. comparison of Jekyll::Post with Jekyll::Post failed

Instead, using the following worked.

{% assign sorted_posts = paginator.posts | sort: :pub_date | reversed %}
{% assign latest_post = sorted_posts | last %}

<!-- do something with latest post -->

{% for post in sorted_posts reversed %}
{% if forloop.first %}<!-- discard the first post -->{% else %}

<!-- iterate over posts -->

{% endif %}
{% endfor %}

Not 100% sure why we need to call reverse twice, but it works.

0
David Jacquel On

Correct syntax to sort you paginator.posts by pub_date :

{% assign sorted_posts = paginator.posts | sort: 'pub_date' %}

{% for post in sorted_posts %}
  <h1><a href="{{ post.url }}">{{ post.title }}</a></h1>
  <p class="author">
    <span class="date">Pubdate : {{ post.pub_date | date: "%b %-d, %Y"}}</span>
  </p>
{% endfor %}

I don't know if the first at the end is supposed to get the first post of the array, but in this case, it's :

{% assign sorted_posts = paginator.posts | sort: 'pub_date' | first %}

---> as we get one post NO loop !

<h1><a href="{{ post.url }}">{{ sorted_posts.title }}</a></h1>
<p class="author">
<span class="date">Pubdate : {{ sorted_posts.pub_date | date: "%b %-d, %Y"}}</span>
</p>