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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.