How to count all the pages per taxonomy while looping through the current page's taxonomies?

Hello people,

Imagine the following situation. You’re on an article page (so a ‘single’). This page also displays the categories and tags of this particular article. I would like to show the total amount of articles for each individual category or tag. It should like this: ‘Philosophy (7)’.

It’s easy to get all categories and tags of a particular page, but in that case I can’t find a way to show the count of those categories and tags.

My code looks like this:

{{ range .GetTerms "categories" }}
  {{ $category := .LinkTitle | lower }}
  {{ $count := .Site.Taxonomies.categories.$category.Count }}
    <a href="{{ .Permalink }}">{{ .LinkTitle }} ({{ $count }})</a>
{{ end }}

This code however gives an error. So, should I do it just completely differently or is there a way to use custom variables in functions like I tried in my code. Because the logic of that code would be the solution.

Would appreciate any help.

{{ range .GetTerms "tags" }}
  {{ $count := .Pages.Len }}
  <a href="{{ .RelPermalink }}">{{ .LinkTitle }} ({{ $count }})</a>
{{ end }}

Thanks a lot, this works!

It’s very hard for me for to be aware of the context and now what options I have (like .Pages). Is there any way I can easily see all the options, or do you just learn that with experience?

The documentation for taxonomy/term structures and methods could use some love. I know this stuff fairly well, but it took me a few attempts to provide an efficient answer to your question.

In some cases you can use jsonify to examine context:

<pre>{{ jsonify (dict "indent" "  ") . }}</pre>

But this fails if the context contains .Pages.


There’s a related open issue:

And corresponding PR:

1 Like

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