Implementing an 11ty readingTime filter

Published on April 13, 2025 - Estimated reading time is 3 minutes
Eleventy

The readingTime filter in 11ty is a custom filter designed to calculate the estimated reading time for content. It assumes an average reading speed of 238 words per minute and provides a user-friendly way to display this information in your layouts.

Implementation details

The readingTime filter was implemented in the eleventy.config.js file. Here's how it works:

  1. Word count calculation: The filter splits the content into words using whitespace as a delimiter and filters out any empty strings. This gives an accurate word count.
  2. Reading time estimation: The word count is divided by 238 (the average reading speed in words per minute) and rounded up to the nearest whole number using Math.ceil.
  3. Output formatting: The filter returns a string in the format "X minute(s)", where X is the calculated reading time.

Here is the code for the filter:

eleventyConfig.addFilter("readingTime", (content) => {
  const wordsPerMinute = 238; // Average reading speed
  if (typeof content !== "string") {
    return "0 minutes";
  }

  const wordCount = content
    .split(/\s+/)
    .filter((word) => word.length > 0).length;
  const readingTimeMinutes = Math.ceil(wordCount / wordsPerMinute);

  return `${readingTimeMinutes} minute${readingTimeMinutes > 1 ? "s" : ""}`;
});

How to use the filter

To use the readingTime filter in your layouts, simply pass the content to the filter. For example, in the note.html layout, you can display the estimated reading time like this:

<span class="note-reading-time">
  Estimated reading is {{ content | readingTime }}
</span>

This will calculate and display the reading time for the content of the note.

Benefits

By adding the readingTime filter, you enhance the usability of your site and provide a better experience for your readers.

Example in action

This page itself uses the readingTime filter to display the estimated reading time at the top. The filter is applied to the content of the note, providing a real-world example of its usage.

Resources