{{craftSnippets}}
Home Articles Plugins Starter theme Components on Github Gists About
  • Home
  • Articles
  • Read time macro for Craft CMS
Posted on Jun 21, 2019 by Piotr Pogorzelski

Read time macro for Craft CMS

Read time macro in github gists
This macro will return read time in human readable format, adjusted to your site locale.
Table of contents:
  • Read time macro overview
  • Macro code
  • How does it work?
  • Read time plugin
  • Further reading

Read time macro overview #

Here's a short summary on read time macro functionality:

  • Read time is calculated based on the assumption that average human reads 256 words per minute.
  • Time returned by the macro will be outputted in human-readable format that is adjusted to the locale of your current website. For example, for english it will be "2 minutes" and for german "2 minuten".
  • Macro will round read time to minutes. If read time is less than one minute, the macro will output less than 1 minute. While 1 minute in this sentence is automatically adjusted to current site locale, less than must be provided by static translations.
  • Text passed to macro will be stripped of HTML to avoid getting misleading results.
  • Words separated by dashes instead of spaces will still be treated as two words.

Macro code #

{% macro readTime(text) %}
{% spaceless %}
    {# settings #}
    {% set wordsPerMinute = 265 %}
    {% set showLessThanMinute = true %}
    {# logic #}
    {% set plaintext = text|striptags|replace({'—': ' ', '–': ' ', '-': ' ', '\n': ' '}) %}
    {% set words = plaintext|split(' ') %}
    {% set minutes = ceil(words|length / wordsPerMinute) %}
    {% set seconds = minutes * 60 %}
    {% set formatter = create({ class: 'craft\\i18n\\Formatter' }) %}
    {% if (words|length / wordsPerMinute) * 60 < 60 and showLessThanMinute %}
        {{'less than'|t ~ ' ' ~ formatter.asDuration(60)}}
    {% else %}
        {{formatter.asDuration(seconds)}}
    {% endif %}
{% endspaceless %}
{% endmacro %}

Advice: for grabbing text taken from multiple fields or sources and mixed with HTML, its good idea to use set with opening and closing tag - like this:

{% set text %}
{{entry.someField}}
{% for block in entry.someMatrix.all() %}
    {{ block.subfield}}
{% endfor %}
{{entry.someOtherfield}}
{% endset %

Thanks to that, you can just use your already existing markup and easily pass it to macro.

How does it work? #

The first part of macro is pretty self-explanatory. We split the text into an array of words, count words and calculate read time. What about create function?

Not every internal function of Craft CMS is available in Twig templates directly. To use asDuration function that outputs time in human readable format, we need to instantiate craft\i18n\Formatter object using create function. You can read more about it on nystudio blog.

Read time plugin #

As an alternative to macro, you can use the Read time plugin.

It also has the ability to return read time in human readable format adjusted to your locale. Other than that, it is able to return exact time, with minutes and seconds, return time as a numeric variable or just process entry and all its related fields automatically.

All in all, I think that for basic usage, the macro will suffice.

Further reading #

  • Craft coding challange - 5 minute read
  • Medium - read time and you

TAGS:
#macro
If you want to get latest updates on Craft CMS tutorials and components, follow me on Twitter or subscribe to RSS feed.
Quick links for this article:
Read time macro in github gists
Articles on blog:
  • Frontend testing for Craft CMS websites with Codeception and Cypress
  • Building reactive Craft Commerce product page with Sprig plugin
  • Dynamically generated PDF attachments for Freeform submissions
  • Using template hooks in Craft CMS
  • Alpine JS modal component for Craft CMS
  • Using template UI elements to extend Craft CMS control panel
  • Matrix within a Matrix - possible solutions for Craft CMS
  • Universal email template for Craft CMS
  • Creating attributes table from entry fields in Craft CMS
  • Namespacing forms in Craft CMS
  • Creating map-based navigation for Craft CMS
  • Placeholder image macro for Craft CMS
  • Building AJAX contact form with Craft CMS
  • Using incognito field plugin for Craft CMS
  • Email footer creator made with Craft CMS
  • Infinite scrolling and lazy loading with Craft CMS
  • Using Javascript in Twig templates with Craft CMS
  • Twig templating tips and tricks for Craft CMS
  • Basic SEO functionality for Craft CMS
  • Working with dates in Craft CMS templates
  • Working with SVG images in Craft CMS templates
  • Responsive and lazy-loaded youtube videos with Craft CMS
  • Debugging and inspecting Twig templates in Craft CMS
  • Creating article excerpts with Twig component in Craft CMS
  • Adding favicons to Craft CMS website
  • Truncating text with Twig macros in Craft CMS
  • Universal language switcher for Craft CMS
  • Read time macro for Craft CMS
  • Using attr() function to render HTML attributes in Craft CMS
  • Building dynamic, AJAX based pagination for Craft CMS
  • How to add Disqus comments to Craft CMS website
  • Ellipsis pagination component for Craft CMS
  • Converting email addresses into links using Twig macro
  • Breadcrumb created from URL for Craft CMS
  • Best developer-oriented Craft CMS plugins
  • Search autocomplete component for Craft CMS
  • RSS feed - template component for Craft CMS
  • Testing emails sent by Craft CMS using Mailtrap
  • Quick edit link - Twig component for Craft CMS
  • Filtering entries in control panel using Searchit plugin
  • Fetching routes into Twig templates in Craft CMS


Frontend testing for Craft CMS websites with Codeception and Cypress

Building reactive Craft Commerce product page with Sprig plugin

Dynamically generated PDF attachments for Freeform submissions

Using template hooks in Craft CMS

Alpine JS modal component for Craft CMS

Using template UI elements to extend Craft CMS control panel

Matrix within a Matrix - possible solutions for Craft CMS

Universal email template for Craft CMS

Copyright ©2023 Piotr Pogorzelski