Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jekyll show post count for sub categories

Tags:

jekyll

liquid

I have a Jekyll site built and for the posts, I have 3 sub-categories.

These categories are: blog examples tips

In each one of these categories I also have sub-categories for html, css and js.

In each post I have front-matter and a categories tag which looks like this as an example:


categories: - blog

- html

I would like to create a loop that outputs the post count for each category. So if under blogs I have 2 posts in each sub-category:

  • blogs
    • HTML
    • html-post1.md
    • html-post2.md
    • css
    • css-post1.md
    • css-post2.md
    • js
    • js-post1.md
    • js-post2.md

How can I loop over this to just display the count instead of outputting each post?

like image 410
marzy Avatar asked Sep 17 '25 01:09

marzy


2 Answers

You can loop directly over your site's categories like this:

<ul>
{% for cat in site.categories %}
    <li>{{ cat[0] }} ({{ cat[1].size }})</li>
{% endfor %}
</ul>

cat[0] is the category's name.
cat[1] is an array of all posts with that category, so cat[1].size is the number of posts.

The resulting HTML will look like this:

<ul>
    <li>HTML (2)</li>
    <li>css (2)</li>
    <li>js (2)</li>
</ul>

Note that the list of categories is unordered by default.
If you want to order it by name or post count, the solution is slightly more complicated.

like image 80
Christian Specht Avatar answered Sep 19 '25 16:09

Christian Specht


For each category you could include a count like this:

  {% assign total = 0 %}
  {% for post in site.posts %}
     {% if post.category == "some_category" %}
      {% assign total = total | plus: 1 %}
     {% endif %}
  {% endfor %}
like image 21
briancaffey Avatar answered Sep 19 '25 16:09

briancaffey