How to add number of articles in the main menu

Hello,

I have a main menu as follows:

{{ $currentNode := . }}
   <ul>
    {{ range .Site.Menus.main }}
    {{- $isCurrent := ( or ( $.IsMenuCurrent "main" . ) ( $.HasMenuCurrent "main" . ) ) -}}
    <li>
      <a {{ if $isCurrent -}} class='current' aria-current='page' {{ end -}} href='{{ .URL }}'>
        {{- .Name -}}
      </a>
    </li>
  {{ end }}

This menu works well but I would like to add for each menu item the number of articles such as books (12).
Sorry but no obvious method either in the Hugo docs or in this forum.
Thanks for help

It’s documented here: https://gohugo.io/functions/len/#len-example-2-counting-pages-with-where

You can count the number of posts for a certain topic, store the number in a variable and publish the variable content with len.

Hope this helps.

If you search in this forum like https://discourse.gohugo.io/search?q=count%20posts you’ll of course get answers. My search term was “count number of posts”.

Thanks a lot Leo and sorry.
I saw the two posts you got but my very limited skills in coding don’t allow me to implement it in the above menu.
I don’t know how to use the following example

<a {{ if $isCurrent -}} class='current' aria-current='page' {{ end -}} href='{{ .URL }}'> {{- .Name -}} </a>{ len (where .Site.Pages "Section" "!=" "") }}
or other examples proposed in the forum.

Actually, I succeeded to display what I wanted with the following code:

  <div class="card">
      <ul>
        {{ range $key, $value := .Data.Terms }}
        <li>
          <a href="{{ (print $key | urlize) | relURL }}">
            {{ $key }}
          </a>
          ({{ len $value }})
        </li>
        {{ end }}
      </ul>
  </div>

But it is displayed only on the single page “site/categories” and not on any other page on the site.
It should be dealt with the terms.html in default layout but I don’t understand the rationale behind this situation.
Help would be much appreciated