For the techno theme I wanted to make custom hb helpers and configuration available to users. To do this I applied an override to the [ghost root]/index.js.
The code below searches for index.js in the current theme folder and runs it.
var ghost = require('./core'),
errors = require('./core/server/errorHandling');
ghost()
.then(function (param) {
var settings = require('./core/server/api').settings;
settings
.read({key: 'activeTheme', context: {internal: true}})
.then(function (result) {
try {
require('./content/themes/' + result.value + '/index')();
}
catch (e) {
//No custom index found, or it wasn't a proper module.
}
});
})
.otherwise(function (err) {
errors.logErrorAndExit(err, err.context, err.help);
});
The theme level index.js injects custom blog variables (from a config file) and hb helpers.
var hbs = require('express-hbs'),
_ = require('lodash'),
downsize = require('downsize'),
blogVariable = require('../../../core/server/config/theme');
module.exports = function() {
//This block allows configuration to be available in the hb templates.
var blogConfig = blogVariable();
var config = require('./config') || {};
blogConfig.theme = config;
//console.log(JSON.stringify(blogConfig));
////Custom hb helpers////
hbs.registerHelper('excerpt', function (options) {
...
return new hbs.handlebars.SafeString(excerpt);
});
...
};
An example of using the custom blog variables is below.
<ul class="list-inline">
<li><a href="{{@blog.theme.author.github}}" class="btn-social btn-outline" data-toggle="tooltip" data-placement="top" title="Github"><i class="fa fa-fw fa-github"></i></a>
</li>
...
Is there a better way to do this in Ghost 0.4.2? I do not like having users override the ghost core index.js file.
There is a blog post explaining how to do this only by modifying the config.js
file, and adding a file to the root directory. I agree with the author that this is more likely to be update-proof. http://zackehh.com/safely-creating-custom-handlebars-helpers/
Add:
require('./helpers')();
To the top of config.js
And add helpers to your helpers.js
file like so:
var hbs = require('express-hbs');
module.exports = function(){
hbs.registerHelper('json', function(context) {
return JSON.stringify(context);
});
};