Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic calculation on Liquid template in Jekyll to calculate estimated reading time

I started using Jekyll 1 week ago with no knowledge in Ruby and I would like to implement the following functionality.

From the Jekyll documentation I can use the following template to calculate the words in an article:

{{ page.content | number_of_words }}

I would like to use this information to calculate an estimated reading time in minutes for the article, based on the assumption of 200 words per minute on average. Which gives the following simple formula:

number_of_words / 200

Without being sure, but based on what I have read about Ruby, I should use {% %} to execute my calculation, but I am not sure if I can use the {{ page.content | number_of_words }} within that, to perform the division.

Here is what I have currently:

.html document:

.
.
<p class="meta">
    {% print {{number_of_words}} / 200 %}
</p>
.
.

I am sure that number_of_words as used above does not exist and I am not sure if print will do the trick there. Any ideas?

like image 836
Rafael Avatar asked Feb 13 '16 02:02

Rafael


1 Answers

Whilst Jekyll is written in Ruby, you normally don’t need to write any Ruby when using it. It uses Liquid, which was designed explicitly to allow users to create page designs without allowing them to run arbitrary code.

Liquid does have tags (Jekyll adds some more), which use {% %}, but in this case I think you might be getting confused with the Erb templating language, which uses <% %> to execute Ruby code.

You can create custom Liquid tags and filters of your own if you need to, but in this case there is the divided_by filter which seems to do what you want:

{{ page.content | number_of_words | divided_by: 200 }}

Note this is integer division, the same as your example would produce, so if the word count is less than 200 the result will be zero. To check for this and only include it if the total is > 0, you can use the assign tag (which can be used with filters) and if tag like this:

{% assign read_time = page.content | number_of_words | divided_by: 200 %}

{% if read_time > 0 %}
Read time: {{ read_time }}
{% endif %}
like image 110
matt Avatar answered Sep 28 '22 02:09

matt