Skip to content

Instantly share code, notes, and snippets.

@zzeneg
Forked from Lerg/index-content.js
Last active August 29, 2015 14:04
Show Gist options
  • Save zzeneg/2d92509d68420cecebc4 to your computer and use it in GitHub Desktop.
Save zzeneg/2d92509d68420cecebc4 to your computer and use it in GitHub Desktop.
// ### Content Helper
//
// *Usage example:*
// `{{content}}`
// `{{content words="20"}}`
// `{{content characters="256"}}`
// `{{content preview="true"}}`
// `{{content preview="true" words="20"}}`
//
// Turns content html into a safestring so that the user doesn't have to
// escape it or tell handlebars to leave it alone with a triple-brace.
//
// Enables tag-safe truncation of content by characters or words.
//
// If preview option is used then only the content before <!--preview--> is returned.
//
// **returns** SafeString content html, complete or truncated.
//
coreHelpers.content = function (options) {
var truncateOptions = (options || {}).hash || {};
truncateOptions = _.pick(truncateOptions, ['words', 'characters', 'preview']);
_.keys(truncateOptions).map(function (key) {
truncateOptions[key] = parseInt(truncateOptions[key], 10);
});
if (truncateOptions.hasOwnProperty('preview')) {
var split = this.html.split('<!--preview-->', 2)
if (split.length > 1) {
return new hbs.handlebars.SafeString(split[0])
}
}
if (truncateOptions.hasOwnProperty('words') || truncateOptions.hasOwnProperty('characters')) {
// Due to weirdness in downsize the 'words' option
// must be passed as a string. refer to #1796
// TODO: when downsize fixes this quirk remove this hack.
if (truncateOptions.hasOwnProperty('words')) {
truncateOptions.words = truncateOptions.words.toString();
}
return new hbs.handlebars.SafeString(
downsize(this.html, truncateOptions)
);
}
return new hbs.handlebars.SafeString(this.html);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment