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
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:
How can I loop over this to just display the count instead of outputting each post?
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 %}
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.