I tried to register handlebar on my express node application, but seems like it doesn't work
const express = require('express');
const hbs = require('hbs');
const expressHbs = require('express-handlebars');
const app = express();
app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs' }));
app.set('view engine', 'hbs');
hbs.registerHelper('if_equal', function(a, b, opts) {
if (a == b) {
return opts.fn(this)
} else {
return opts.inverse(this)
}
});
In .hbs file I run this code
{{#if_equal x "my_string"}}
x is "my_string"
{{else}}
x isn't "my_string"
{{/if_equal}}
Then I received this error
Error: Missing helper: "if_equal" handlebars
The problem is that you're using two different view engines. express-handlebars & hbs.
Your .hbs
files are being rendered with express-handlebars
, while you're registering the helper to hbs
.
Drop express-handlebars
, and drop this line:
app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs' }));
The extension .hbs is the default one for hbs:
Using hbs as the default view engine requires just one line of code in your app setup. This will render .hbs files when res.render is called.
app.set('view engine', 'hbs');
hbs.registerHelper('if_equal', function(a, b, opts) {
if (a == b) {
return opts.fn(this)
} else {
return opts.inverse(this)
}
});
//remove require('hbs');
const expressHbs = require('express-handlebars');
const hbs = expressHbs.create({
// Specify helpers which are only registered on this instance.
helpers: {
if_equal: function(a, b, opts) {
if (a == b) {
return opts.fn(this)
} else {
return opts.inverse(this)
}
}
}
});
//The following example sets up an Express app to use
//.hbs as the file extension for views:
app.engine('.hbs', expressHbs({extname: '.hbs'}));
app.set('view engine', '.hbs'); //with dot
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With