Skip to content

Instantly share code, notes, and snippets.

@jankais3r
Created July 29, 2015 21:49
Show Gist options
  • Save jankais3r/faea3a2621baff32ddde to your computer and use it in GitHub Desktop.
Save jankais3r/faea3a2621baff32ddde to your computer and use it in GitHub Desktop.
Ghost - custom excerpt tag

This code snippet implements manual control over excerpts in Ghost.

You will need to modify 2 files and 1 setting:

  1. Ghost/core/server/helpers/content.js - this one will get overwritten during Ghost update
  2. Ghost/content/themes//partials/loop.hbs - this one has to be modified for each theme
  3. 'Blog Footer' section of 'Code Injection' settings page

Default behavior is having whole articles displayed on the front page. If you want to display only an excerpt, put <!--preview--> at the position you want to cut the article.

This enables precise control over article previews.

// # Content Helper
// Usage: `{{content}}`, `{{content words="20"}}`, `{{content characters="256"}}`
//
// 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.
var hbs = require('express-hbs'),
_ = require('lodash'),
downsize = require('downsize'),
downzero = require('../utils/downzero'),
content;
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('words') || truncateOptions.hasOwnProperty('characters')) {
// Legacy function: {{content words="0"}} should return leading tags.
if (truncateOptions.hasOwnProperty('words') && truncateOptions.words === 0) {
return new hbs.handlebars.SafeString(
downzero(this.html)
);
}
return new hbs.handlebars.SafeString(
downsize(this.html, truncateOptions)
);
}
else if ((truncateOptions.hasOwnProperty('preview')) && (this.html.indexOf('<!--preview-->')) > 0) {
var split = this.html.split('<!--preview-->', 2);
excerpt = split[0];
excerpt += '&hellip;\n';
return new hbs.handlebars.SafeString(excerpt);
}
var random = Math.floor((Math.random() * 1000000) + 1);
var complete = this.html;
complete += '\n<p id="del_' + random + '"></p>';
return new hbs.handlebars.SafeString(complete);
};
module.exports = content;
<!-- .post-header -->
<div class="post-content">
<p>{{content preview="true"}}</p>
<p class="read-more"><a class="read-more-link" href="{{url}}" title="{{title}}">Continue reading &rarr;</a></p>
</div>
<!-- .post-content -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment