May 28th, 2021 - written by Kimserey with .
After five years of writing with over 250 posts, I realised that it would be nice to have a page with all post categories that I’ve discussed so far. In today’s post we’ll look at how we can leverage site.categories
from Jekyll to construct a category page.
This post will start from the previous base we wrote in How to create a blog with Jekyll.
The most important part is to tag your posts in the front matter:
1
2
3
---
categories: [xyz]
---
This will make the post and the category available under site.categories
. Then we can create a categories.html
page:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
---
title: Categories
---
<div class="container pb-3">
<h2 id="categories">Blog Categories</h2>
{% assign sorted_categories = site.categories | sort %}
{% for category in sorted_categories %}
{% assign category_name = category | first % }
<div id="{{ category_name }}">
{{ category_name }}
<ul>
{% assign category_name = category | first % }
<div id="{{ category_name }}">
{{ category_name }}
<ul>
{% for post in site.categories[category_name] %}
<li>
<span class="font-italic">{{ post.date | date_to_string: "ordinal", "US" }}</span> - <a href="{{ post.url }}">{{ post.title }}</a>
</li>
{% endfor %}
</ul>
</div>
{% endfor %}
</div>
which we’ll be able to access from /categories.html
.
In this template, we assigns the sorted categories to sorted_categories
so that they can be displayed in alphabetical order:
1
{% assign sorted_categories = site.categories | sort %}
we then loop over the sorted_categories
and take the category_name
:
1
{% assign category_name = category | first % }
We take the first value which returns the title of the category.
And with the category name, we are able to access all the posts for this category site.categories[category_name]
which we then loop over to print each posts for that category:
1
2
3
4
5
{% for post in site.categories[category_name] %}
<li>
<span class="font-italic">{{ post.date | date_to_string: "ordinal", "US" }}</span> - <a href="{{ post.url }}">{{ post.title }}</a>
</li>
{% endfor %}
And that’s it! Hope that helped and see you on the next post!