Jekyll category lists

I am a big fan of Jekyll, even this blog was first built using an old version of Jekyll. Recently I built a support site for the my employer using Jekyll just like the one that Basecamp has.

Basically on a post beside the main content there is a column that lists the title of posts which are in the same category as the current post. Previously I had the following code to make Jekyll spit out the list.

Basically on a post beside the main content there is a column that lists the title of posts which are in the same category as the current post. Previously I had the following code to make Jekyll spit out the list.

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

However after upgrading to Jekyll 2.0 the list vanished. The funny thing is it skip the for loop.

Understanding page.category and site.category

The key to this problem was the way Jekyll process the Front-matter, especially if you like to write camel case or capital letters like I do. This was how I wrote the category Front-matter for some of my posts.

    ----
    category: Review    
    // other variables
    ----

If you did site.category on a post you will get Review, exactly how you wrote it in your Post Front-Matter. However starting with Jekyll 2.0, the developers decided to change the variables for categories to lower case, except site.category.

Hence doing site.categories.['Review'] is the same as site.categories.[page.category] which will return nothing as Jekyll does not know the category Review. But doing site.categories.['review'] will return an array of posts under category Review, since Jekyll now understand the lower case review category variable.

To fix my problem all I had to do is force site.category to lower case like so.

{% assign cat = page.category | downcase %}
{% for post in site.categories.[cat] %}
    <a href="{{ post.url}}">{{ post.title }}</a></li>
{% endfor %}

Since many hands will be touching the repo for the support site, I figured this will be a dumb proof way to making sure that it will always work no matter who writes the category Front-matter. Now anyone can write the category as camel case or capital letters and be sure that Jekyll will return the right category.

When I was stuck I asked a question on Github, which I eventually answered myself.

- comments -

comments powered by Disqus