Tag Archives: if equal helper in handlebarjs

How to write custom ifequal helper function in handlebars.js?

Handlebar Html Template: Put this template in any html page source.

<script id="handlebarHtml" type="text/handlebar-template">{{firstname}}{{lastname}}
{{#ifequal "a" "b"}} 
	if block
{{else}}
	Else block
{{/ifequal}}
</script>
#Put this code in any global javascript files and make sure function is available to the caller function.
Handlebars.registerHelper('ifequal', function(v1, v2, options) {
    if (v1==v2) return options.fn(this);
    else  return options.inverse(this);
 });

Handlebars javascript compilation code.

var json = {firstname: "Follow", lastname: "cybersecurity"}
var output = Handlebars.compile($("#handlebarHtml").html());
output(json);

Output of above code is:

Followcybersecurity
Else block