Skip to content

Hugo: Count entries in Taxonomy

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:

  {{ 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.

  {{ 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.

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
To leave a comment you must approve it via e-mail, which will be sent to your address after submission.
Form options