UPDATE 1/30/24: I just discovered that Hugo already has a system variable called .ReadingTime which does this automatically. I updated my code to use that.
1{{ .ReadingTime }} minute{{ if (ne .ReadingTime 1) }}s{{ end }}
My site is generated using a static site generator by the name of Hugo. It’s fast because it’s powered by the open-source programming language Go and styled with the lightweight CSS Framework Bulma. It’s also difficult to hack because there is no database behind it; it’s just a bunch of text files in Markdown format stored on a Git repository. Every time I add something new, my site is regenerated into static HTML files which then auto-deploy using Netlify.
I modeled my Bulma template off of other cool sites I discovered, and one feature I enjoyed seeing is an estimate of how long it takes to read a blog article because then I know what to expect going into the article. It’s simple math:
- Count the number of words in the article.
- Divide that by the average words read per minute.
- Voilà.
There are a range of speeds, but they seem to be somewhere between 238 and 260 words per minute for silent reading. I assumed the unhappiness experienced by a reader who took longer than they were told would be worse than the happiness folks would experience if they got done sooner, so I went with a conservative 220 wpm.
But I sometimes write concise articles like this one, and since I never wanted it to say that it would take zero minutes, I added a second function that ensured the minimum it would ever show is one minute. How did I do? Were you done with this page in less than a minute!?
Below is the Go code that auto-generates this for me on each blog I write auto-magically! 🪄✨
1{{- $minRead := math.Round (div (countwords .Content) 220.0) }}
2{{- $minRead := math.Max $minRead 1 }}