Ghost/core/frontend/helpers/excerpt.js
Hannah Wolfe 5bf12939e4
Updated eslint-plugin-ghost & fixed resulting failures
- I recently added a bunch of strict rules to our eslint plugin around returns: ca9af37866
- These mostly are issues that occur whilst writing code, that you spot and fix as you're developing, but they're annoying to notice/find and eslint can be used to flag them quickly
- There are of course, edge cases where you don't need to return from array fns, but this rule also suggests better patterns might be available
- For our excert helper and new assertEvent helper, I've updated the code to use simpler patterns that are easier to read, so as to avoid the warnings
- For our old API I've simply disabled the rule as we're about to delete this code
2022-02-21 12:30:12 +00:00

46 lines
1.3 KiB
JavaScript

// # Excerpt Helper
// Usage: `{{excerpt}}`, `{{excerpt words="50"}}`, `{{excerpt characters="256"}}`
//
// Attempts to remove all HTML from the string, and then shortens the result according to the provided option.
//
// Defaults to words="50"
const {SafeString} = require('../services/rendering');
const {metaData} = require('../services/proxy');
const _ = require('lodash');
const getMetaDataExcerpt = metaData.getMetaDataExcerpt;
module.exports = function excerpt(options) {
let truncateOptions = (options || {}).hash || {};
let excerptText;
if (this.custom_excerpt) {
excerptText = String(this.custom_excerpt);
} else if (this.html) {
excerptText = String(this.html);
} else if (this.excerpt) {
excerptText = String(this.excerpt);
} else {
excerptText = '';
}
truncateOptions = _.reduce(truncateOptions, (_truncateOptions, value, key) => {
if (['words', 'characters'].includes(key)) {
_truncateOptions[key] = parseInt(value, 10);
}
return _truncateOptions;
}, {});
if (!_.isEmpty(this.custom_excerpt)) {
truncateOptions.characters = this.custom_excerpt.length;
if (truncateOptions.words) {
delete truncateOptions.words;
}
}
return new SafeString(
getMetaDataExcerpt(excerptText, truncateOptions)
);
};