Ghost/core/server/helpers/reading_time.js
Aileen Nowak dbd22d7447 Feature: {{reading_time}} theme helper (#9217)
closes #9200

- Registered new server helper `{{reading_time}}`.
- Added new global util `word-count` based on the util in Ghost admin, which returns the number of words in an HTML string.
- Based on the word count of the post html, the helper calculated the estimated reading time:
   - 275 words per minute
   - additional 12 seconds when post has feature image
- Renders a string like 'x min red', unless reading time is less than a minute. In this case, the rendered string is '< 1 min read'.
2017-11-06 18:40:07 +00:00

42 lines
1.1 KiB
JavaScript

// # Reading Time Helper
//
// Usage: `{{reading_time}}`
//
// Returns estimated reading time for post
var proxy = require('./proxy'),
schema = require('../data/schema').checks,
SafeString = proxy.SafeString,
wordCountUtil = require('../utils/word-count');
module.exports = function reading_time() {// eslint-disable-line camelcase
var html,
wordsPerMinute = 275,
wordsPerSecond = wordsPerMinute / 60,
wordCount,
imageCount,
readingTimeSeconds,
readingTime;
// only calculate reading time for posts
if (!schema.isPost(this)) {
return null;
}
html = this.html;
imageCount = this.feature_image ? 1 : 0;
wordCount = wordCountUtil(html);
readingTimeSeconds = wordCount / wordsPerSecond;
// add 12 seconds to reading time if feature image is present
readingTimeSeconds = imageCount ? readingTimeSeconds + 12 : readingTimeSeconds;
if (readingTimeSeconds < 60) {
readingTime = '< 1 min read';
} else {
readingTime = `${Math.round(readingTimeSeconds / 60)} min read`;
}
return new SafeString(readingTime);
};