Sorting tags in Jekyll

A short tip on how to sort your tags in your Jekyll blog

By Stef van den Ham — November 30 2016

On this blog I list all the used tags in the sidebar. I realised these tags were listed randomly so wanted to know if you could sort them alphabetically.

Turns out you can.

Tagging posts

In your posts, make sure you tag your posts in the meta section:

title: Your awesome title
	- something
	- here
	- three

Now, Jekyll is clever and knows about your tags and stores them in site.tags. To display a list of them, use the following snippet:

{% assign sorted_tags = site.tags | sort %}
{% for tag in sorted_tags %}
  {% assign t = tag | first %}
  {% assign posts = tag | last %}
  	<a href="/tags/# {{ t | downcase | replace:' ','-'}}">
		{{t | downcase | replace:' ','-' }} 
  		<span>({{ posts | size }})</span>
{% endfor %}

So first Jekyll gets all tags, and pipes them through the sort function. Next we iterate over them and link to a page passing the tag for optional use on the target page. Behind the tag we can use the size pipe to show how many posts are tagged with the current tag.

Good stuff.

If you have any questions feel free to reach me at @stefvdham or in the comments below.

Happy coding!

Tags: jekyll


As always, if you have any questions or comments, you can find me on Twitter.

Be notified of new posts. Subscribe to the RSS Feed.