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.
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:
len .Pages
) by the number of site pages (len $.Site.Pages
)$pct
14
and $pct
. In other words, 14px
is the minimum
font size.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.
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>
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>
There you go - check out the footer of https://blog.mikeski.net to see it in action!