Like many before me, I wanted to tag posts, display those tags and have a page for each tag which listed tagged posts. As usual, step 1 is to ask the internet where I found two helpful articles:
- https://longqian.me/2017/02/09/github-jekyll-tag/
- https://blog.lunarlogic.io/2019/managing-tags-in-jekyll-blog-easily/
Armed with these, let us accomplish these tasks.
Tag the posts
Simply list the tags in the frontmatter:
---
layout: post
title: Tags for Jekyll posts in 2022
tags: jekyll
---
List the tags
A page’s tags are kept in page.tags
so you can display
them in the post
layout with something like
<span>
{% for tag in page.tags %}
{% capture tag_name %}{{ tag }}{% endcapture %}
<a href="/tag/{{ tag_name }}">
<code><nobr>#{{ tag_name }}</nobr></code>
</a>
{% endfor %}
</span>
Similarly, in the home
layout, do:
{% for post in site.posts %}
<li>
<span>{{ post.date }}</span>
<span>
{% for tag in post.tags %}
{% capture tag_name %}{{ tag }}{% endcapture %}
<a href="/tag/{{ tag_name }}">
<code><nobr>#{{ tag_name }}</nobr></code>
</a>
{% endfor %}
</span>
<h3>
<a href="{{ post.url | relative_url }}">
{{ post.title | escape }}
</a>
</h3>
</li>
{% endfor %}
Note that each tag is wrapped in a link to /tag/some-tag
.
We make the end-points of these links next.
Tag pages
The plan is to have a folder /tag
at top-level containing
files some-tag.md
for each tag some-tag
. Their content
is just:
---
layout: tag-page
title: "Tagged with #some-tag"
tag: some-tag
---
Make a layout tag-page.html
thusly:
---
layout: default
---
<div>
{{ content }}
<h1>Posts tagged #{{ page.tag }}</h1>
<ul>
{% for post in site.tags[page.tag] %}
<li>
<span>{{ post.date }}</span>
<span>
{% for tag in post.tags %}
{% capture tag_name %}{{ tag }}{% endcapture %}
<a href="/tag/{{ tag_name }}">
<code><nobr>#{{ tag_name }}</nobr></code>
</a>
{% endfor %}
</span>
<h2>
<a>{{ post.title | escape }}</a>
</h2>
<p>{{ post.description }}</p>
</li>
{% endfor %}
</ul>
</div>
Here we see how things have moved on since 2017 when
longqian.me
was writing: then you have to build site.tags
yourself
with a cunning piece of liquid
. Now jekyll
provides it
for us.
Finally, with
lunarlogic,
we want the machine to make the tag pages when a new tag is
used. She provides a hook that you put in _plugins
for
this. At first I though I was out of luck because GitHub
Pages runs Jekyll in safe mode and so won’t execute the hook.
But then the penny dropped: I don’t need this to run on
GitHub. Each tag file creation is a one-off event that can
be done by Jekyll locally.
So mission accomplished and another piece of the jigsaw is in place.