6

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?

1 Answer 1

11

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 %}
2
  • Thanks for that is working! A quick last one, for your note about 0 if less than 200, you would this {{ page.content | number_of_words | divided_by: 200 }} be used in an if statement to check > 0 so if is 0 to ignore printing that one?
    – Rafael
    Commented Feb 13, 2016 at 3:06
  • Wonderful. I will need to study further about Liquid as it looks quite interesting. Thanks for your help. @matt
    – Rafael
    Commented Feb 13, 2016 at 3:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.