Skip to content

Instantly share code, notes, and snippets.

@piotrpog
Created June 21, 2019 21:22
Show Gist options
  • Save piotrpog/94e7d32173b9dfc6a917cb46e2893e05 to your computer and use it in GitHub Desktop.
Save piotrpog/94e7d32173b9dfc6a917cb46e2893e05 to your computer and use it in GitHub Desktop.
This macro will return read time in human readable format, adjusted to your site locale. More info: http://craftsnippets.com/articles/read-time-macro-for-craft-cms
{% macro readTime(text) %}
{% spaceless %}
{# v1 #}
{# 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 %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment