How to add estimated Reading Time to Posts in Statiq

Published on

Last Updated on

Estimated Reading Time: 1 min

You can install StatiqHelpers as a Nuget Package if you just want a module to add to your website.

In this tutorial, I will show how to use the reading time calculated in How to calculate reading time to use in a Statiq module to add reading time for our posts.

To add a module to Statiq, we can inherit from one of the provided 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 document 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)) }
                })
            .Yield();
    }
}
  • 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

Further Reading