Jekyll Capitalize Categories
I just wasted two hours solving a problem caused by throwing away good information.
Jekyll has a
site.categories collection that keeps a list of all categories on
a site. As it should. For some crazy reason, though, that list throws away case
formatting. For example, a category called “My Category” would be stored as “my
I iterate over
site.categories to build my navigation menu, so I wanted that
case-sensitivity back. I found a hack that works. Keep reading to see my solution.
Note: There is almost certainly a clean fix by adding plugins, but I am using GitHub Pages for my site, and do not control the Jekyll configuration.
This would create a series of links for category pages. Where the first piece of
information stored in a category is its name. So in the case of
containing the following:
['cat1', 'cat2'] Jekyll would produce:
But let’s use a real-world example and see where this falls apart. Assume we have
the categories “Reading List” and “My Thoughts”. Here,
['reading list', 'my thoughts']. Note the stripped case.
Our code above would produce:
So note here: the
capitalize filter only capitalizes the first character of the
filtered string (not all words.) I could find no combination of filters that gave
me the title-case, camel-case or otherwise solution that I wanted.
Note also: the space in the URL is debatably okay.
The Hacky Solution
So I’ll cut to the chase. I said I found a solution. On the individual
object inside the
site.categories.CATEGORY collection, there is a variable
category if you use a single category per post.
So basically, if your YAML FrontMatter looks like:
page element viewing this post will have a
element that has “Jekyll Issues” with correct capitalization.
In my case, I only use the single
category: FrontMatter, not the plural. So
all my posts have a
Note the two different capitalizations. In the
category object here,
is the mangled name (eg- ‘jekyll issues’),
category is the list of posts in
that category. Therefore
category is the first
post in a category.
And since each
post in my system has a
post.category defined by the YAML
category.category retrieves the non-mangled category name
from the first post in that category (eg- ‘Jekyll Issues’).
To display the Jekyll category name preserving case (eg- Title Case or whatever):
Note: This only works when you use
category: in the YAML FrontMatter. If you
categories: to apply several categories to a post, you’re on your own.