I try to register my own helper methods to express-handlebars to use it in views and partials. My goal is to create a for a search function in my navigation partial. But I dont even get my helper working on my index view.
I tried a lot of thinks..
App.js
const exphbs = require('express-handlebars')
const helpers = require('./public/helper/hbs-helper');
const express = require('express')
const app = express()
const hbs = exphbs.create({
layoutsDir: path.join(__dirname, 'views/layouts'),
partialsDir: path.join(__dirname, 'views/partials'),
helpers: helpers
})
app.enable('trust proxy')
app.engine('handlebars', hbs.engine)
app.engine('.hbs', exphbs({
extname: '.hbs'
}))
app.set('view engine', 'handlebars')
app.set('views', path.join(__dirname, 'views'))
hbs-helper.js
module.exports = {
sayHello: function(elem) {
return 'hello!'
}
}
index.hbs - here i tried everything, but not at the same time ;):
<p>{{sayHello}}</p>
<p>{{#sayHello}}</p>
<p>{{sayHello this}}</p>
It doesnt matter if put "elem" to the function definition, it still doesnt work.
I also tried to implement the given example from https://github.com/ericf/express-handlebars with foo and bar helper (not importing them with require(), I really did the same), but it doesnt work for me. It never displays any of the return values.
Do u guys have any ideas?
The Answer from Vivasaayi worked for me! can't register handlebar helpers Just use following code
helpers.js
let register = function(Handlebars) {
let helpers = {
sayHello: function(elem) {
return 'hello!'
}
};
if (Handlebars && typeof Handlebars.registerHelper === "function") {
for (let prop in helpers) {
Handlebars.registerHelper(prop, helpers[prop]);
}
} else {
return helpers;
}
};
module.exports.register = register;
app.js
const exphbs = require('express-handlebars')
const hbs = exphbs.create({
layoutsDir: path.join(__dirname, 'views/layouts'),
partialsDir: path.join(__dirname, 'views/partials')
})
require("./pathto/helper.js").register(hbs.handlebars);