Just want to add a few ideas since this question is already 3 years. I'm using Express 4 as well with express-handlebars (Also nodejs 8.11 LTS). In the app.js (created by express generator).
const exphbs = require('express-handlebars');
const hbsHelpers = require('handlebars-helpers')();
const hbs = exphbs.create({
// Specify helpers which are only registered on this instance.
defaultLayout: 'main',
extname: '.hbs',
helpers: hbsHelpers,
});
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
Tried both above answers but couldn't get them working. But noticed that in the Usage section of handlebars-helpers documentation It says: The main export returns a function that needs to be called to expose the object of helpers.
The express-handlebars create function also support the helpers parameter as an object, such as:
const hbs = exphbs.create({
// Specify helpers which are only registered on this instance.
defaultLayout: 'main',
extname: '.hbs',
helpers: {
tsnumber: () => { return Math.round((new Date()).getTime() / 1000); },
},
});
As you can see in this example, I defined one helper called tsnumber (returns Unix style timestamp), and what helpers get is just an object.
To further extend this functionality by combining the helper I defined (tsnumber) and the express-handlebars, we can use Object.assign.
The new structure will be:
config/hbsHelper.js
node_modules/
app.js
The config directory is a folder I created to combine two libraries.
The content of config/hbsHelper.js is:
const hbsDefaultHelpers = require('handlebars-helpers')();
const extra = {
tsnumber: () => { return Math.round((new Date()).getTime() / 1000); },
};
const merged = Object.assign(extra, hbsDefaultHelpers);
module.exports = merged;
Then in the app.js
const exphbs = require('express-handlebars');
const hbsHelpers = require('./config/hbsHelpers');
const hbs = exphbs.create({
defaultLayout: 'main',
extname: '.hbs',
helpers: hbsHelpers,
});