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.
The readingTime
filter was implemented in the eleventy.config.js
file. Here's how it works:
Math.ceil
.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" : ""}`;
});
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.
By adding the readingTime
filter, you enhance the usability of your site and provide a better experience for your readers.
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.