How to count total number of child menus?

Struggling with something seemingly simple…

How do I go about using len to count the total number of child menus (if there are any)?

Test code:

{{- range .Site.Menus.main }}
    {{ if .HasChildren }}
    {{ $children := len .Children }}
    {{ print $children }}
      <li>
       ....
      </li>
    {{ end }}
{{ end }}

The above prints the individual number of child menus each parent menu has. However, I want to count the total number of child menus for all parent menus.

e.g. If parent menu A has 7 child menus and parent menu B has 2 child menus, I’d like to print a count of 9.

Is this possible? Should it be done outside the range statement?

{{ $x := 0 }}
{{ range site.Menus.main }}
  {{ $x = add $x (len .Children) }}
{{ end }}
{{ $x }}
2 Likes

@jmooring This works! Took me a few minutes but I also understand why it works. Thank you once again for a swift response, much appreciated.

Just brief follow up. Is it possible to perform this calculation outside of the range?

My ultimate goal it to split the child menu items equally(ish) between two <ul> columns after determining the total child menus present.

No. You need to range through the map to obtain the count.

But you could range once to get the count, and then range again to render.

1 Like

@jmooring Good idea. Thank you again.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.