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.
Tags must be defined in the post YAML Front Matter.
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.
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.
The tag array is available in the
Determining Whether Tags Should Be Displayed
size attribute of the tags array can be checked to determine whether they should be displayed.
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.
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.
Once assembled, the code to display the tags is not very complicated.
The result for this post is:
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.