How I added a stats page to my Hugo site

April 5, 2022

2 minute read

stats page screenshot

I recently added a stats page to my site, after being inspired by a few Micro.blog sites I came across.

Turns out Micro.blog uses Hugo for the published content part, and it’s really easy to add stats to your own Hugo site using the same code.

The stats page is a plugin for Micro.blog, and you can grab the code off the GitHub repo. You may be able to just drop in the layouts and static folders into your site, link the CSS in your header, and use the shortcodes, but my setup is a little different.

My blog posts live in content/blog, and the stats plugin expects content/posts. And I wanted to customize the output a little.

So I decided to make it a page layout for my site, and then in my stats.md front matter I set layout: stats. You can view the code here.

The chart does use JavaScript, but there’s not an easy way around that.

I really like Amit Gawande’s work on this, especially the tag cloud - take a look at the logic going on here to make the tags larger or smaller depending on the post count:

<h3 class="post-stats-hd">Category Cloud for Posts</h3>
<div class="categorycloud">
    {{ if ne (len $.Site.Taxonomies.categories) 0 }}
      {{ $largestFontSize := 1.4 }}
      {{ $smallestFontSize := 1.0 }}
      {{ $fontSpread := sub $largestFontSize $smallestFontSize }}
      {{ $max := add (len (index $.Site.Taxonomies.categories.ByCount 0).Pages) 1 }}
      {{ $min := len (index $.Site.Taxonomies.categories.ByCount.Reverse 0).Pages }}
      {{ $spread := sub $max $min }}
      {{ $fontStep := div $fontSpread $spread }}
        {{ range $name, $taxonomy := $.Site.Taxonomies.categories }}
          {{ $categoryCount := len $taxonomy.Pages }}
          {{ $currentFontSize := (add $smallestFontSize (mul (sub $categoryCount $min) $fontStep) ) }}
          {{ $weigth := div (sub (math.Log $categoryCount) (math.Log $min)) (sub (math.Log $max) (math.Log $min)) }}
          {{ $currentFontSize := (add $smallestFontSize (mul (sub $largestFontSize $smallestFontSize) $weigth)) }}
            <a href="{{ "/categories/" | relURL }}{{ $name | urlize }}" 
            class="categorycloud-item" style="font-size: {{ $currentFontSize }}rem;">
              {{ $name }}<sup>{{ $categoryCount }}</sup>
            </a>
        {{ end }}
    {{ end }}
</div>

Tagged with hugo meta web

336 words

  Reply via email