[SOLVED] Adding a counter to menu item

Hi

I’m trying to add a job counter to a menu item. Something like "Jobs (2)"
I have found that
{{ len .Site.Sections.jobs }}
gives me the correct count when used separately, but when I put it in the range to render the menu (see below), it doesn’t work anymore.

{{ range .Site.Menus.main }}
{{ if eq .Identifier "jobs" }}
<li><a href="{{.URL}}">{{.Name}}<span class='job-count'>{{ len .Site.Sections.jobs }}</span></a></li>
{{ else }}
<li><a href="{{.URL}}">{{.Name}}</a></li>
{{end}}
{{end}}

Any ideas why that is? Or how this could be fixed?

Thanks!

@nnDjeff Not at a computer to test this (on my phone), but I’m guessing this is because it’s inside the loop. Try assigning it to a variable outside the loop (range) and then add it…

{{$jobCount := len .Site.Sections.jobs}}
{{range...
...
<span class="job-count">{{$jobCount}}</span>
...
{{ end }}
1 Like

@rdwatters Oh wow! That indeed worked perfectly!
Can’t believe I didn’t think of using that…

Thanks a lot!

1 Like