Writing on Tablets Tech stuff from @yeltzland

Writing a Category Index Page for Jekyll

I’ve added a Posts by Category page to the site, as now there are a few posts on here I thought it would be useful to be able to browse them quickly.

As I’ve mentioned before, this site is statically generated using Jekyll which is great but it can be challenging at times to do anything slightly different.

How Jekyll works is that each post is a Markdown file with some meta-data (also known as Front Matter) at the start. For example, this post has this meta-data:

The offline generator can then use this meta data in the templates as required.

I use the categories in two places:

  1. The category labels used at the end of each post showing the category a post is in (and linking through to a section of the index page)
  2. In the categories index page itself to group the pages by category

Templates in Jekyll use the Liquid templating system from Shopify, which is pretty flexible if a little obtuse at times.

For example, here’s the template I wrote for the category index page:

Basically what this does is a hell of a lot of work to get:

  1. A unique list of category values in a concatenated string (get_items)
  2. A count of how many categories there are (num_words)

We then go through each category name in sorted order, and go and get the posts in that category.

Clear as mud really, but luckily I’d built something very similar already on another site a while back with a lot of help from the Internet.

The one downside is that I can’t find any way to do a case-insensitive sort of the categories. According to the documentation, there should be a sort_natural which does exactly what I want, but I couldn’t get it to work 😒

The workaround is to only use lower-case categories (I couldn’t face mis-casing iPad and iOS - too ugly), which isn’t perfect but it will do for now.

[Update: I added some old posts that had title casing for the categories, so gave up on the lower-case only, and will continue to search for a case-insensitive sort soultion]

P.S. This was all written on my Mac and not on my iPad - turns out there are limits on my patience, especially when copy and pasting code between files. Don’t judge me.

Blogging Jekyll