Blogs | Sep 17, 2021

Building a Tag Index with Jekyll and Liquid

by Blaize Stewart

Jekyll and Liquid provide a powerful yet easy-to-use set of tools for creating websites through both the plugins provided by Jekyll and the template markup provided by Liquid. While an integral part of Jekyll, Liquid is a stand-alone project widely implemented in other projects, including many other static site generators. The Jekyll page and post model provides enough data to create logic with Liquid that adds nice addendums to your websites.

For informational and reference websites, Liquid can create a tag index page. It can collate your posts by tags and then sort the tags alphabetically, making it easy for a user to find related information, similar to an index in a book.

Create a new markdown file called tags.md In the tags.md file, paste in the following code. This code is pure Liquid templating. The code creates a “slugified” version of the tag so that it can create an anchor tag (an internal link) using an id field on the HTML anchor in the document. This allows you to provide a hashtag in the URL. Browsers will typically automatically scroll to the anchor in the document if the id is present in the document.


title: Tag Index
layout: default

{% assign sorted_tags = site.tags | sort %}
{% for tag in sorted_tags %}

{{ tag | first }}

    • {% for post in tag[1] %}

    • {{ post.title }}

{% endfor %}

{% endfor %}

 

That’s it. Redeploy or test with Jekyll serve your site, and you will have a tag index page.

Optionally, you can create links to the topics on your posts. Create a new custom layout called “tagged-post.html” or something like that in the _layouts folder in your site directory. You can also override a common default layout like “post.html”. Now, paste in the following code. You can inherit from another layout by using a layout header. This one inherits from default.


---
layout: default
---

{{ page.title | escape }}

{{ content }}

|{% for tag in page.tags %}
|
{% endfor %}

 

This will add a row of links to the bottom of each post or page with a link back to your tag index. That’s it.

You can see this in action here and also get a complete site here:

wArtboard 1wArtboard 1wArtboard 1ShapewArtboard 2wArtboard 2wArtboard 2RSS Iconscrewdriver-wrenchArtboard 2wArtboard 2wArtboard 2