Interactive tags in Jekyll
jekyll javascriptThe problem
This blog (at least for now) is being hosted on Github Pages. It’s a great platform for hosting static websites, and it’s free. The only downside is that it doesn’t support server-side code and every dynamic content has to be generated at build time using Jekyll. This is great for a simple blog like this one, but it has some limitations: for example, I can’t use a server-side language to generate a list of tags for my blog posts and then filter the posts by the tag.
I found examples of how to implement interactive tags in Jekyll (e.g. Jekyll Tags on Github Pages), but they were not suitable for my needs. I wanted fully automated tag filtering without the need to manually update the tag list every time I add a new tag to a blog post.
The solution
I’ve decided to use JavaScript to filter the blog posts by tags. I opted to go with a simple solution: I’ve created a separate page for tags, and I’ve added a script that filters the blog posts by the tag. By default, all the blog posts are hidden:
<div class="posts">
{% for post in site.blogs %}
<a href="{{ post.url }}">
<div class="post-card {{ post.tags | join ' ' }}" style="display: none">
<h3>{{ post.title }} </h3>
<div class="post-card-description">
<p> Tags: {{ post.tags | join ', ' }} </p>
<p> {{ post.date | date_to_string: "ordinal" }} </p>
</div>
</div>
</a>
{% endfor %}
</div>
When the page is loaded, the script reads the URL and extracts the tag from it. Then it filters the blog posts by the tag and displays them.
Here’s the script:
var url = window.location.href;
console.log(url);
var tag = url.split("?").pop();
console.log(tag);
var elements = document.getElementsByClassName(tag);
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = "";
}
The advantage of this solution is that it doesn’t require any server-side code, and it’s fully automated and requires only one additional page that handles the tag filtering. But, I would be first to admit that this is not the most elegant and scalable solution, but it works and I think it’s good enough for a simple blog like this one.
