Estimated Reading Times in Twig

 — 2 Min Read

When I set out to redesign and rebuild this site, I knew I wanted to ditch WordPress for something much lighter and simpler—preferably flat-file-based and with good markdown support. I tried Jekyll, Kirby, Anchor and others. I was almost ready to roll my own until I finally stumbled upon Pico by Gilbert Pellegrom. The single-directory structure and Twig template engine were the two selling points for me.

One particular thing I wanted to achieve was an estimated reading time for each article. Of course, there's no out-of-the-box way to do this but, with a little math, it's not hard.

I'm setting a variable which takes the character-length of any given article, divided by the average character count of an English word, 4.5, and once again by the average reading speed of 180wpm. I'm then rounding that figure to 1 decimal place, to give a nicely formatted estimate.

Here's the code in Twig syntax:

{% set rt = (content | length / 4.5 / 180) | number_format(1) %}

Nice, right? You could take it further and convert that figure into a timestamp, but I find '1.7 Minute Read' easier to digest than '1:42 Minute Read'.

Update 26 July, 2013

Since I'm now powering this site with Jekyll, I've temporarily disabled the reading time feature. Twig was apparently better at math and number formatting than Liquid! I'll be restoring the feature soon and update this article accordingly.

Update 28 July, 2013

Today I restored and improved the read time feature. It is also now available as a Jekyll plugin. Read the follow up post here.