Register the helper you need and use it.
Here’s an example of several helpers I have.
var register = function(Handlebars) {
var helpers = {
isSinglePrice: function(arr, options) {
if(arr.length === 1) {
return options.fn(this);
}else{
return options.inverse(this);
}
},
choosePriceIcon: function(position){
if(position === 0){
return "person";
}else if(position === 1){
return "group";
}else if(position === 2){
return "groups";
}
},
numberFormat: function (value, options) {
// Helper parameters
var dl = options.hash['decimalLength'] || 2;
var ts = options.hash['thousandsSep'] || ',';
var ds = options.hash['decimalSep'] || '.';
// Parse to float
var value = parseFloat(value);
// The regex
var re = '\\d(?=(\\d{3})+' + (dl > 0 ? '\\D' : '$') + ')';
// Formats the number with the decimals
var num = value.toFixed(Math.max(0, ~~dl));
// Returns the formatted number
return (ds ? num.replace('.', ds) : num).replace(new RegExp(re, 'g'), '$&' + ts);
}
};
if (Handlebars && typeof Handlebars.registerHelper === "function") {
for (var prop in helpers) {
Handlebars.registerHelper(prop, helpers[prop]);
}
} else {
return helpers;
}
};
module.exports.register = register;
module.exports.helpers = register(null);
Just create as many helper methods as you need to make the comparisons you need and use it the way you think best.
And here as you use:
var exphbs = require('express-handlebars');
var handlebars = exphbs.create({
layoutsDir: path.join(__dirname, "views/layouts"),
partialsDir: path.join(__dirname, "views/partials"),
defaultLayout: 'index',
extname: 'hbs',
helpers: require("./helpers/hbs.js").helpers
});
EDIT: Here is an example of how you assign the handlebars engine, with the helpers registered above:
const app = express();
app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');
app.set('views', './views')
Now it’s up to you. I hope I’ve helped.
friend, managed to do what you needed, using my answer? If you need anything else, comment! I hope to have helped.
– Mateus
continues the problem
Error: Parse error on line 24:
... {{#if _id == postagem.categoria
-----------------------^
Expecting 'OPEN_SEXPR', 'ID', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', got 'EQUALS'
– Bernardo Lopes
Ué continues the problem because you haven’t changed the code! Vc need to create a helper and use it! Vc understood what handlebars helpers are for?
– Mateus
I created the helper
ifCompare: function (a, b, options) {if (a == b) { return options.fn(this); } return options.inverse(this);}
Apparently it’s working fine– Bernardo Lopes