I wanted to count the number of pages tagged 100daysToOffload
but couldn’t
find a simple solution.
Here are a couple of options that work. We create a shortcode and in your org
file pass the wanted tag to it in the variable tagname
, like so:
@@hugo:{{< tag-count tagname="MyWantedTag" >}}@@
The shortcode(s)
Create a file layouts/shortcodes/tag-count.html
and add the code below.
Preferred approach
My preferred approach is to use the existing .Site.Taxonomies
variable:
{{ len (.Site.Taxonomies.tags.Get (lower (.Get "tagname"))) }}
What is happening here?
(.Get "tagname")
- Returns the value of the variable
tagname
; in the above example this would beMyWantedTag
(lower ...)
- Converts the result to lower case. Note that tags are always lower case
(.Site.Taxonomies.tags.Get ...)
- Gets the list of pages that are tagged with the wanted term
len ...
- Returns the length of the list of tagged pages, i.e. the number of pages with the wanted tag
Alternative #1 - filter
We can use the range
function to loop over all of the tags and their values
like this…
{{ range $key, $value := .Site.Taxonomies.tags }}
{{ if in $key (.Get "tagname") }}
{{ len $value }}
{{ end }}
{{ end }}
Alternative #2 - brute force
The final option is based on this post where we loop over all the pages and increment a counter if we find a page with the right tag.
<!-- (re)set the counter to 0 -->
{{ $.Scratch.Set "tagCounter" 0 }}
<!-- increment counter if post contains the wanted tag-->
{{ range .Site.RegularPages }}
{{ if in .Params.tags $tagname }}
{{ $.Scratch.Add "tagCounter" 1 }}
{{ end }}
{{ end }}
<!-- Return the result -->
{{ $.Scratch.Get "tagCounter" }}