Andy Taylor

Andy Taylor

Jekyll Reading Time

Some of my posts now include an estimated reading time. I did this by taking the Liquid Filter, number_of_words and—based on a reading rate of 180wpm—used other Liquid filters to convert it to an approximate reading time. Here’s the template code:

{{ page.content | number_of_words | append: '.0' | divided_by:180 | append: 'min' }}

For this post, it will output: 1.6944444444444444min

Unfortunately the X.XXXmin figure is a bit verbose. I’d prefer a whole number, or at least X.Xmin. Without append: '.0' I was getting a whole number, but it wasn’t rounded. So 1.9min would be 1min. Liquid provides more filters which could limit the figure to X characters, but they haven’t been implemented by Jekyll.

A reading time on very short posts seemed a bit silly. I found a clever bit of template logic on Stack Overflow that enabled me to only show it on posts that are greater than 250 words. It’s a bit hacky, but it essentially uses truncatewords (without actually truncating the words), then establishes if the post is longer than the truncated length to create an if statement.

{% capture truncated_content %}
  {{ page.content | truncatewords: 250 }}
{% endcapture %}
{% if page.content != truncated_content %}
  {{ page.content | number_of_words | append: '.0' | divided_by:180 | append: 'min' }}
{% endif %}

Because I couldn’t get Liquid/Jekyll to round the number. I wrapped it in a span with the class .time. My friend Josh wrote a jQuery script for me that rounds it to the nearest whole number:

<script type='text/javascript'>
  $(document).ready(function() {
    $(".time").text(function (index, value) {
      return Math.round(parseFloat(value));
    });
  });
</script>

Have a comment? @me on Twitter.