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

April 18th, 2016 • 6 min read
Recently React Storybook came out. It's a tool to isolate your React Components to develop and design them outside of your app. I'll be walking through setting it up
February 11th, 2012 • 2 min read
The Spotify Preview build has expired
August 6th, 2013 • 2 min read
Let me show you how you can get syntax highlighted output from cat in the terminal