Nice tagcloud with Hugo

· by Artem Sidorenko · Read in about 2 min · (285 words)

In my old blog with octopress I used the tag cloud plugin with logarithmic distribution for calculation of tag sizes. The rendered tag cloud was pretty nice from the optic side. All existing approaches I saw for hugo(1, 2) were not so nice, the main reason is the usage of logarithmic distribution in the calculation of tag size.

You can compare the rendering with and without log function below:


comparison


math.Log template function was added to Hugo in release 0.25, so now it can be used within templates to create nice tag clouds.

Based on the code from Hendrik Sommerfeld, here is the implementation with log function:

{{ if not (eq (len $.Site.Taxonomies.tags) 0) }}
    {{ $fontUnit := "rem" }}
    {{ $largestFontSize := 2.0 }}
    {{ $largestFontSize := 2.5 }}
    {{ $smallestFontSize := 1.0 }}
    {{ $fontSpread := sub $largestFontSize $smallestFontSize }}
    {{ $max := add (len (index $.Site.Taxonomies.tags.ByCount 0).Pages) 1 }}
    {{ $min := len (index $.Site.Taxonomies.tags.ByCount.Reverse 0).Pages }}
    {{ $spread := sub $max $min }}
    {{ $fontStep := div $fontSpread $spread }}

    <div id="tag-cloud" style="padding: 5px 15px">
        {{ range $name, $taxonomy := $.Site.Taxonomies.tags }}
            {{ $currentTagCount := len $taxonomy.Pages }}
            {{ $currentFontSize := (add $smallestFontSize (mul (sub $currentTagCount $min) $fontStep) ) }}
            {{ $count := len $taxonomy.Pages }}
            {{ $weigth := div (sub (math.Log $count) (math.Log $min)) (sub (math.Log $max) (math.Log $min)) }}
            {{ $currentFontSize := (add $smallestFontSize (mul (sub $largestFontSize $smallestFontSize) $weigth) ) }}
            <!--Current font size: {{$currentFontSize}}-->
            <a href="{{ "/tags/" | relLangURL }}{{ $name | urlize }}" style="font-size:{{$currentFontSize}}{{$fontUnit}}">{{ $name }}</a>
        {{ end }}
    </div>
{{ end }}

Here is the entire sidebar file of this blog. The tag cloud section can be used on the similar way with other bootstrap based themes.