How to add estimated Reading Time to Posts in Statiq

This entry was posted on

  • Statiq
  • tutorial
  • snippet

In this tutorial, I will be showing how to use the reading time calculated in How to calculate reading time to use in a Statiq module so that we can add reading time for our posts.

To add a module to Statiq, we can inherit from one of the provide base module classes. In this case, we can inherit from the ParallelModule class as the engine can process the documents in any order. We also need to overload the ExecuteInputAsync() method to execute this module for each of the documents in the pipeline.

public class GenerateReadingTime : ParallelModule
    protected override async Task<IEnumerable<IDocument>> ExecuteInputAsync(IDocument input, IExecutionContext context)
        using var textReader = input.GetContentTextReader();
        var content = await textReader.ReadToEndAsync();

        return input.Clone(
                new MetadataItems
                    { MetaDataKeys.ReadingTime, _readingTimeService.GetReadingTime(content, context.GetInt("ReadingTimeWordsPerMinute", 200)) }
  • Line 5-6: Get the content associated with the document as a string.
  • Line 8: Clone the document by adding new metadata items.
  • Line 10-11: Add a new metadata item with key Reading_time_and a value obtained from a call to GetReadingTime. We use a_ReadingTimeWordsPerMinute setting to override the default value of 200 words per minute.
  • Line 11: Convert the document into an enumerable.

We can now use it on our website. You can see an example below.

Reading time example
Reading time example


More like this

Ankur Sheel © 2021
Connect with me