Hugo: Count entries in Taxonomy

Posted by ads' corner on Wednesday, 2022-06-08
Posted in [Hugo]

For the “PostgreSQL Person of the Week” interviews I’m using Hugo as static blogging engine. Part of every interview is the list of tags, which links this interview to other similar interviews. However until recently no one really knew if a tag is popular or just used in this interview. I wanted to change this, and add the tag count behind every tag.

The way I use Hugo I have the previews also online, and I don’t want to count any interviews which are not published (still drafted) when counting entries for a tag.

Tags in Hugo are taxonomies, which is a user-defined grouping of content.

The original code in the overview page (themes/pglive/layouts/_default/single.html) looked like this:

1
2
3
4
5
6
7
8
9
  {{ if .Params.tags }}
    <br/>
    <span class="list-timeline-tags em-alt">
      <span class="type-dark-6">{{ if len .Params.tags | eq 1 }}Tag{{ else }}Tags{{ end }}: &nbsp;</span>
      {{ range .Params.tags }}
        <a href="/tags/{{ . | urlize }}">{{ . }}</a> &nbsp;&nbsp;
      {{ end }}
    </span>
  {{ end }}

This loops over all tags in the current posting, and generates one link per entry.

In the new version I need to apply some filters before I can count the entries. First I need to exclude all pages which are still in review (drafted interviews), and second I only want posts, not news entries. Then I can count all interviews which include the current tag.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  {{ if .Params.tags }}
    <span class="list-timeline-tags em-alt">
      <span class="type-dark-6">{{ if len .Params.tags | eq 1 }}Tag{{ else }}Tags{{ end }}: &nbsp;</span>
      {{ $tagCount := 0 }}
      {{ $nonDraft := where $.Site.RegularPages ".Draft" false }}
      {{ $posts := where $nonDraft "Section" "==" "post" }}
      {{ range .Params.tags }}
        {{ $tagCount = len (where $posts "Params.tags" "intersect" (slice .)) }}
        <a href="/tags/{{ . | urlize }}">{{ . }}</a> ({{ $tagCount }})&nbsp;&nbsp;
      {{ end }}
    </span>
  {{ end }}

Now every tag has a count after the name. Much more useful. See the result here. I added the same functionality in a couple other places, and also in the tag list overview.


Categories: [Hugo]