How to count rendered posts in a specific folder?

I’m trying to figure out how to count rendered posts in a specific content/ folder.

This is my content/ folder structure:

posts/
  alpha/
    post-1.md
    post-2.md
    post-3.md
    post-4.md
  beta/
    post-1.md
    post-2.md
  omega/
    post-1.md
    post-2.md
    post-3.md

I’d like to be able to count the rendered posts located in each of alpha, beta and omega folder, in order to get something like that:

Number of rendered posts in the alpha/ folder: 4
Number of rendered posts in the beta/ folder: 2
Number of rendered posts in the omega/ folder: 3
Total of rendered posts: 9

How can I achieve this?

See How to count pages in a "where" statement?

If I use:

{{ len (where .Site.RegularPages "Section" "==" "posts/alpha") }}

or

{{ len (where .Site.RegularPages "Section" "==" "alpha") }}

…Hugo returns 0.

Wrap it in a variable first.

For example:

{{ $posts := (where .Site.RegularPages "Section" .Section) }}
{{ $postCount := len $posts }}{{ $postCount }}

EDIT
With the above you do not need to manually enter each section’s name. You call this in your list templates as you please with {{ $postCount }}

I understand but what if I want to use this logic in my website homepage which is just a static landing page without any post listing?

You should be able to fetch the post count of a Hugo Section with .GetPage

I’m not sure how I would use that… could you explain please?

Ok. I will it make it very plain then.

You simply wrap the code from my previous post that is used to render the post count of a section with a .GetPage function for the specific section you want. To render the post count of the “alpha” section on your homepage.

{{ with .Site.GetPage "section" "alpha" }}
{{ $posts := (where .Site.RegularPages "Section" .Section) }}
{{ $postCount := len $posts }}
{{ $postCount }} Posts
{{ end }}
1 Like