Hugo Tag Clouds for Taxonomy and Sections

Thursday Feb 20, 2020

Let’s see an easy way to create a tag cloud for hugo. The basic idea is that for any section or taxonomy term (or really any set of pages) we scale the display font based on how many pages are in the section. The larger the percentage of the pages, the larger the font.

How it works - Sections

First, we need to select our set of pages. For example, if we wanted to use Sections we could do the following:

    <ul class="list-inline">
        {{ range $.Site.Sections }}
            <li class="list-inline-item">
                {{ partial "scaled_tag_cloud_link.html" . }}
            </li>
        {{ end }}
    </ul>

This selects all of the site sections and renders the scaled tag cloud as a list item. Let’s look at the scaled_tag_coloud_link.html partial:

    {{ $pct := math.Floor (mul (div ( float (len .Pages))  (len $.Site.Pages)) 100) }}
    {{ $fontSize := cond (gt $pct 14) $pct 14  }}
    <a class="dropdown-item" style="font-size:  {{ $fontSize }}px;" href={{ .Permalink }}>{{ .Name }}</a>

How it works:

  1. Let’s unpack the first line:
    • Divide the pages in the current section (len .Pages) by the number of site pages (len $.Site.Pages)
    • Multiply by 100
    • Round down (e.g. 45.2343) becomes 45
    • Let this be the variable called $pct
  2. The second line says take the greater value of 14 and $pct. In other words, 14px is the minimum font size.
  3. The last line displays a link to the list with the font-size we just calculated.

That’s it, now we have a tag cloud with the terms sized based on the number of pages in it relative to the total site pages.

Taxonomies

We can change the range function to get a tag cloud by taxonomy terms, too:

    <ul class="list-inline">
        {{ range (where .Site.Pages "Kind" "taxonomy") }}
        <li class="list-inline-item">
            {{ partial "scaled_tag_cloud_link.html" . }}
        </li>
        {{ end }}
    </ul>

Combined

We can also use multiple categories to get tag clouds:

    <ul class="list-inline">
        {{ range (where .Site.Pages "Kind" "taxonomy") }}
        <li class="list-inline-item">
            {{ partial "scaled_tag_cloud_link.html" . }}
        </li>
        {{ end }}

        {{ range $.Site.Sections }}
        <li class="list-inline-item">
            {{ partial "scaled_tag_cloud_link.html" . }}
        </li>
        {{ end }}
    </ul>

Summary

There you go - check out the footer of https://blog.mikeski.net to see it in action!