Skip to content

Instantly share code, notes, and snippets.

@gthln
Forked from mrmwiebe/excerpt.js
Last active August 29, 2015 14:28
Show Gist options
  • Save gthln/cd06bf2e1a2a9da245a2 to your computer and use it in GitHub Desktop.
Save gthln/cd06bf2e1a2a9da245a2 to your computer and use it in GitHub Desktop.
Custom excerpt.js
// # 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"
/*
Added optional ability to use 2 <!--excerpt--> tags in your posts to specify exactly what will be
shown as your excerpt. It will add an elipsis where the second tag is.
e.g. Sample Post:
# Post Header
Here is some content that I don't want in my excerpt. <!--excerpt-->But this is what
I want to show up in my excerpt on my main blog page<!--excerpt-->. This won't show
up either. Handy!
NOTE: If there are no <!--excerpt--> tags, it will default to your preferred default of words & characters.
By: Marlon Wiebe (mwiebe.com)
Adapted from: thomas_na & Lerg (https://ghost.org/forum/using-ghost/15991-customize-post-preview/)
*/
var hbs = require('express-hbs'),
_ = require('lodash'),
downsize = require('downsize'),
excerpt;
excerpt = function (options) {
var truncateOptions = (options || {}).hash || {},
excerpt;
truncateOptions = _.pick(truncateOptions, ['words', 'characters']);
_.keys(truncateOptions).map(function (key) {
truncateOptions[key] = parseInt(truncateOptions[key], 10);
});
if (this.html.indexOf("<!--excerpt-->") > -1) {
var split = this.html.split('<!--excerpt-->', 2);
var output = split[1];
return new hbs.handlebars.SafeString(output);
} else {
/*jslint regexp:true */
excerpt = String(this.html);
// Strip inline and bottom footnotes
excerpt = excerpt.replace(/<a href="#fn.*?rel="footnote">.*?<\/a>/gi, '');
excerpt = excerpt.replace(/<div class="footnotes"><ol>.*?<\/ol><\/div>/, '');
// Strip other html
excerpt = excerpt.replace(/<\/?[^>]+>/gi, '');
excerpt = excerpt.replace(/(\r\n|\n|\r)+/gm, ' ');
/*jslint regexp:false */
if (!truncateOptions.words && !truncateOptions.characters) {
truncateOptions.words = 50;
}
return new hbs.handlebars.SafeString(
downsize(excerpt, truncateOptions)
);
}
};
module.exports = excerpt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment