Sorting tags in Jekyll

Posted November 30th 2016 • 2 min read

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
tags:
    - 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:

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

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 @hyra or in the comments below.

Happy coding!