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!

Stay up to date

Want to know when a new post comes out and stay in the loop on tips, tricks and gotchas? Consider signing up for the Mindthecode newsletter.

Comments

Keep reading

November 7th, 2017 • 3 min read
Boilerplate apps are great. They let you get your next project up and running quickly, and usually provide some form of structure you can follow. But the best boilerplate app is the one you code yourself.
April 27th, 2020 • 35 min read
Exploring the options we have as developers to retrieve a large dataset. We will go through the process of finding the data we need, and then write the code to make that date ours in a format we can use.
November 28th, 2016 • 12 min read
Maintaining a local server for your projects can become cumbersome and can cause conflicts with your co-workers. Streamlining this with Docker makes sure everyone is in on the same page.