Search code examples
rubyjekyllliquid

How do I create a loop that display each category and its post count?


I have a blog that I built with Jekyll. On the side bar I want to include a nav bar that list each category along with total number of posts for each. This is what I have right now:

<h2>Post Categories</h2>
<nav>
  {% for category in site.categories %}
    <h3><a href="/{{ category }}">{{ category }}</a> ({{ category | size }})</h3>
  {% endfor %}
</nav>

I'm not on my computer that has Ruby and Jekyll installed so I can't build the site locally. But is this something that will work?


Solution

  • From the Liquid docs for the size filter:

    Size: Returns the number of characters in a string or the number of items in an array.

    Here's a full listing of the available vars using Jekyll, including site.categories.

    Instead of calling size on your category var itself, you need to call it on the last argument, which is where the array of posts are hiding:

    <h2>Post Categories</h2>
    <nav>
      {% for category in site.categories %}
        <h3><a href="/{{ category | first }}">{{ category | first }}</a> ({{ category | last | size }})</h3>
      {% endfor %}
    </nav>