Adding custom helper functions in Ghost

Add custom handlebars helper functions by modifying the core files of your Ghost blog. Not meant for Ghost Pro users.

Adding custom helper functions in Ghost

You cannot add a custom helper function in Ghost. You just cannot and it's simple as that. But what if I tell you, you can?*

Editing the core

That's right. The only way to add customer helper function is by editing the core files and by doing so, you risk losing these changes whenever you update Ghost to a newer version. Still want to add a custom handlebars helper function? Continue reading.

Let's say we want to create a helper function to add line breaks:

Handlebars.registerHelper('breaklines', function(text) {
    text = Handlebars.Utils.escapeExpression(text);
    text = text.replace(/(\r\n|\n|\r)/gm, '<br>');
    return new Handlebars.SafeString(text);
});

Since Ghost uses express-hbs, we have to refactor to use functions instead:

// Inside current/core/frontend/helpers/linebreaks.js
//
// # Linebreaks Helper
//
// Usage:  `{{linebreaks html_string}}`
//
// Returns string

const {SafeString} = require('../services/proxy');

module.exports = function linebreaks(string, options) {
    const  text = string.replace(/(\r\n|\n|\r)/gm, '<br>');
    return new SafeString(text);
};

Next, register the function:

// Inside current/core/frontend/services/theme-engine/handlebars/helpers.js

const registerAllCoreHelpers = function registerAllCoreHelpers() {
    // Register theme helpers
    registerThemeHelper('asset', coreHelpers.asset);
    
    [..]
    
    // This is your custom file.
    registerThemeHelper('linebreaks', coreHelpers.linebreaks);

   [..]    
};

That's it! Restart your Ghost application ghost restart and you're all set. Remember you'll need to backup these two files before you upgrade Ghost.

Ghost Pro

*Ghost maintainers have no plans for having custom helper functions anytime soon. Do head over to their online forum to voice your concerns for having custom helper functions. If you use Ghost as a headless cms, chances are you'll never need handlebars helper functions ✌🏼.