← til

Listing categories of Jekyll collection

April 20, 2020

I've just reorganized the TIL page to alphabetically list all the categories I'm writing about. TIL is a custom collection of this Jekyll website[1], so I couldn't simply use site.categories to get categories of this collection, even though it uses categories in its front matter:

layout: post
title: Listing categories of Jekyll collection
categories: jekyll

I had to resort to some Liquid hackery.

{% assign til = site.til %} 
{% assign categories =  til | map: 'categories'
                            | join: ','
                            | split: ','
                            | group_by: category
                            | sort: "name" %}
{% for category in categories %}
    <h2>{{ category.name | capitalize }}</h2>

    {% assign posts = til | where: "categories", category.name
                          | sort: "date" 
                          | reverse  %}

    {% for post in posts %}
        <a href="{{ post.url }}">
          {{ post.title }}

          {{ post.date | date: "%B %-d, %Y" }}
    {% endfor %}
{% endfor %}

The end result:

  • categories are sorted alphabetically
  • posts inside each category are sorted by date, most recent first

The biggest problem with this approach is the constraint of a single category per post. If multiple categories are used, the post will get listed multiple times in the TIL index, one time for each category.

  1. I've written another post explaining how to add a hidden collection to Jekyll.
@shime_sh Hrvoje Šimić
0 kudos