Handlebars Helpers
Helpers in Handlebars.js are reusable functions that can be added to data to change its behavior in some way.
Handlebars provides several built-in helpers such as if, each, unless etc. (For built-in helper, refer http://handlebarsjs.com/builtin_helpers.html)
Creating custom Handlebars Helpers
We can create our own helper functions in Handlebars using the registerHelper() method.
Here, we will be creating a custom helper formatTelephone that can format a phone number as per our need.
Here is the code for adding the helper:
Handlebars.registerHelper('formatTelephone', function(phoneNumber) { if (phoneNumber.length == 10) { return "(" + phoneNumber.substring(0, 3) + ") " + phoneNumber.substring(3, 6) + "-" + phoneNumber.substring(6); } else { return phoneNumber; } });
The first parameter ‘formatTelephone’ is the helper name and second parameter is a callback function that defines what the helper would do.
This helper formats a passed phone number such that the first 3 digits are within a pair of parenthesis and the next 3 digits are separated from the last 4 using a hyphen.
For example, 1234567890 will be formatted as (123)456-7890
Here is the complete code :
<!DOCTYPE html> <html> <head> <title>Handlebars js Helper</title> <script type="text/javascript" src="handlebars-v4.0.10.js"></script> </head> <body> <div id="displayArea"></div> <script id="myTemplate" type="text/x-handlebars-template"> {{#employees}} <h1>Employee Name : {{this.name}}, Phone : {{formatTelephone this.phoneNumber}}</h1> {{/employees}} </script> <script type="text/javascript"> var tmpHtml = document.getElementById("myTemplate").innerHTML; var template = Handlebars.compile(tmpHtml); var data = { employees : [ { name : "John", age : 22, phoneNumber : "1234567890" }, { name : "Dave", age : 34, phoneNumber : "4147862398" }, { name : "Emily", age : 39, phoneNumber : "7781237695" } ] }; Handlebars.registerHelper('formatTelephone', function(phoneNumber) { if (phoneNumber.length == 10) { return "(" + phoneNumber.substring(0, 3) + ") " + phoneNumber.substring(3, 6) + "-" + phoneNumber.substring(6); } else { return phoneNumber; } }); var html = template(data); document.getElementById("displayArea").innerHTML += html; </script> </body> </html>
Output :
© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post