Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.