When I started this blog, I knew I wanted to tag the posts and use tag based navigation. Unfortunately, my Jekyll theme didn’t display post tags so I modified it tonight. This post covers how to add tags to posts and how to display them.

Defining Tags

Tags must be defined in the post YAML Front Matter.

---
layout: post
title:  A Post Without Tags
---

There are two alternatives to define the tags. The first one is the simplest. Just add the tags, separating them by at least one space. This is suitable when the tags are single words.

---
layout: post
title:  A Post With One Word Tags
tags:   FirstTag SecondTag    ThirdTag
---

If the tags are made of more than one word, the second alternative is needed. The tags must be in a YAML array, separated by at least one space.

---
layout: post
title:  A Post With Multi Word Tags
tags:   [ First Tag, Second Tag,    Third Tag ]
---

Displaying Tags

The tag array is available in the post.tags variable.

Determining Whether Tags Should Be Displayed

The size attribute of the tags array can be checked to determine whether they should be displayed.

{% if post.tags.size > 0 %}
  # Display tags
{% endif %}

Displaying the Singular or Plural Form

When there’s only one tag, “Tag:” should be displayed instead of “Tags:”. All this code must be on a single line unless spaces will be added in place of new lines.

Tag{% if post.tags.size > 1 %}s{% endif %}:

Displaying Tags

The Liquid template engine used by Jekyll offers a lot of filters. The sort filter is useful to sort the values of an array and the join filter can be used to separate each entry of an array by a string. It is useful to separate each tag by a comma.

{{ post.tags | sort | join: ", " }}

Assemble Everything

Once assembled, the code to display the tags is not very complicated.

{% if post.tags.size > 0 %}
  Tag{% if post.tags.size > 1 %}s{% endif %}:
  {{ post.tags | sort | join: ", " }}
{% endif %}

The result for this post is:

Tags: Jekyll, Tags

Conclusion

With tagged posts, pages to list posts by tag would be nice. Jekyll doesn’t generate those by default, but plugins exist to do it. Unfortunately, plugins are not allowed on GitHub Pages. The workaround would be to generate the Jekyll site locally with plugins enabled, and commit only the output to the GitHub repository.