Using liquid to sort posts alphabetically

Jacques Tardie picture Jacques Tardie · Jan 24, 2012 · Viewed 15.3k times · Source

Is there a way to sort a number of posts alphabetically, using Jekyll?

I have something like this now:

{% for post in site.categories.threat %}
<li><a href="{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}

It works, but the posts are jumbled up. Would look much nicer if they were sorted alphabetically I think.

Thanks

Answer

Christian Specht picture Christian Specht · Jul 14, 2014

It can be done without a plugin, which means that it works with Github Pages.

You have to use some ugly string manipulation tricks, though.
I used a similar approach to implement a tag page (that lists all posts for each tag).

Same approach, slightly modified:

{% capture posts %}
  {% for post in site.posts %}
    |{{ post.title }}#{{ post.url }}
  {% endfor %}
{% endcapture %}
{% assign sortedposts = posts | split: '|' | sort %}
{% for post in sortedposts %}
    {% assign postitems = post | split: '#' %}
    <a href={{ postitems[1] }}">{{ postitems[0] }}</a><br>
{% endfor %}

Beware:

You need two different separator characters inside the first loop (and of course again in the split calls later on).
In order for this to work, both characters must not occur in any of the post titles or URLs!!

I'm using | and # in this example, which works for me (I just tested it with my blog). But you might need to use different characters, depending on your post titles and how your URLs are constructed.


Bonus:

If you want to display only the posts in a certain tag/category (and not all posts), you can change the first for loop (the one inside the capture) to one of these:

{% for post in site.tags['whatever'] %}

{% for post in site.categories['whatever'] %}