Jekyll – Custom Sort Order Next and Previous Posts with Loop

To get the next and previous posts with a custom sort order with Jekyll, we need to do some fairly ridiculous logic with liquid.

Why is this worth posting? I’ve needed to do this multiple times, and this is the kind of thing you should be able to copy from the internet. Unfortunately each time I need it, “it doesn’t work” because of unintuitive liquid scope.

For example, you can’t increment the i variable in the below example inside of an if statement, but all’s well if you do it at the top level.

Anyway here’s the generic way to sort a Jekyll collection by an arbitrary sort key:

{% assign posts = site.products | sort: 'position' %}
{% assign i = 0 %}

{% for post in posts %}

  {% assign nextIndex = i | plus: 1 %}
  {% assign prevIndex = i | minus: 1 %}

  {% if post.title == page.title %}
  	we've looped through posts in our custom sort order 
  	until we've found our matching post.
    {% if forloop.first %}

      if it's the first loop, then the previous post is the last item
      {% assign prev = posts.last %}

    {% else %}

      otherwise, the previous post is the previous index
      {% assign prev = posts[prevIndex] %}

    {% endif %}

    {% if forloop.last %}

      if it's the last loop, then the next post is the first item
      {% assign next = posts.first %}

    {% else %}

      otherwise, the next post is the next index
      {% assign next = posts[nextIndex] %}
    {% endif %}

  {% endif %}

  {% assign i = i | plus: 1 %}
{% endfor %}


Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s