Is it possible in Handlebars to check if a string is equal to another value without registering a helper? I can\'t seem to find anything relevant to this in the Handlebars r
You cannot directly compare the strings in handlebars and you have to use a helper. I tried the above solutions with my Koa app and couldn't register the helper. The below code worked for me and i think this should work for express apps as well. I hope this helps someone.
Code in server.js
var handlebars = require('koa-handlebars');
const isEqualHelperHandlerbar = function(a, b, opts) {
if (a == b) {
return opts.fn(this)
} else {
return opts.inverse(this)
}
}
app.use(handlebars({
viewsDir: './app/views',
layoutsDir: './app/views/layouts',
defaultLayout: 'main',
helpers : {
if_equal : isEqualHelperHandlerbar
}
}));
Code in HBS file where fruit is the variable to be compared:
<select id={{fruit}}>
<option >Choose...</option>
<option value="apple" {{#if_equal fruit "apple"}} selected {{/if_equal}}>Apple</option>
<option value="mango" {{#if_equal fruit "mango"}} selected {{/if_equal}} >Mango</option>
</select>