With the help of Liquid tags we can have estimated reading time into Jekyll.
Wikipedia suggests a proofreading speed on screen of 180 words per minute (WPM) so here we divide the total content words with 180 (but you can have your own average WPM).
{% assign reading_time = content | strip_html | number_of_words | divided_by: 180 %}
{{ reading_time }} min read
With the release of Jekyll 2.2.0 it depreciated the liquid tag rounding method {{ reading_time | round }}
so we can not get rounded value from the above technique. Here we only get 1.6 = 1 or 2.4 = 2 value.
To get estimated rounded value reading time to the nearest whole number we code more here.
What some of the following Liquid tags do for us:
content
: Your current post content on a page.2strip_html
: Remove all the HTML tags in a page content.number_of_words
: Count all the words in a content.append: '.0'
: Show all the decimal numbers.divided_by: 180
: Divide the total content words by 180.{% assign reading_time = content | strip_html | number_of_words | append: '.0' | divided_by: 180 %}
{% if reading_time < 0.5 %}Less than a minute read
{% elsif reading_time >= 0.5 and reading_time < 1.5 %}1 minute read
{% elsif reading_time >= 1.5 %}<span class="reading-time">{{ reading_time }}</span> minutes read
{% endif %}
Here we get 1.67777 or 2.43333 so until the Jekyll implementation of Liquid rounding method for now we wrap the {{ reading_time }}
with the .reading-time
class so that the following jQuery will help us to get the rounded value to the nearest whole number.3
// Reading time - jQuery script that rounds it to the nearest whole number
$(document).ready(function() {
$(".reading-time").text(function (index, value) {
return Math.round(parseFloat(value));
});
});
Now with the help of above jQuery snippet we get the actual rounded value to the nearest whole number 1.6777 = 2 or 2.43333 = 2. That’s what we want to get.
If you don’t want to use jQuery or any other techniques but only want to utilize pure Liquid tags then following codes will definitely help you to get estimated reading time into Jekyll.
{% assign reading_time = content | strip_html | number_of_words | plus:91 | divided_by:180 %}
{% if reading_time <= 1 %}
{% assign reading_time = '1' | append:' min read' %}
{% else %}
{% assign reading_time = reading_time | append:' min read' %}
{% endif %}
Now if you tag {{ reading_time }}
where you want to show the post estimated reading time, then it will output as 1 min read
or 2 min read
accordingly to your contents.
Estimated reading time = Total content words / Average reading words per minute ↩
If you’re implementing estimated reading time in paginator i.e. {% for post in paginator.posts %}
condition you should change content
to post.content
. Also know that page.content
tag will include your current post front matter title
text. ↩
Place the jQuery snippet below the jQuery loaded library otherwise it won’t work! ↩