Wednesday, October 25, 2017

How To Add Custom Helpers on Handlebars?

You can extend handlebars with your own custom helpers. This allows you to create complex logic using handlebar’s expression system. There are 2 kinds of helpers, a function helper and a block helper. The difference is that one is meant for a single expression and the other uses a block expression.

Custom Function Helpers
Creating function helpers is relatively easy. To create one, we have to register it using the registerHelper() method. It takes the name of the helper and the helper function as arguments. Handlebars.js takes whatever is returned from the helper function and writes it out to the template, so be sure to always return a string from your custom helpers.

To write an expression helper function to output a formatted phone number, you could define the following helper:
Handlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {
  phoneNumber = phoneNumber.toString();
  return "(" + phoneNumber.substr(0,3) + ") " + phoneNumber.substr(3,3) + "-" + phoneNumber.substr(6,4);
You would use the formatPhoneNumber helper in a template like this:
{{formatPhoneNumber phoneNumber}}

Custom Block Helpers
Custom block helpers are also registered with the Handlebars.registerHelper method. When a helper is used with a block, Handlebars will pass the contents of the block compiled into a function to the helper.

Here's an example block helper that compare the option with a value, letting the contents know whether a value is equal to option. If the option is an equal to a value, helper just returns the 'selected' attribute else return empty string. This helper is useful to add a 'selected' attribute conditionally on any of the option elements.
Handlebars.registerHelper("selected", function(option, value) {
 if (option === value) {
        return 'selected';
    } else {
        return '';

You would use the selected helper in a template like this:
<select name="countries" >
 <option  value="{{code}}" {{selected code "46" }>{{country_name}}({{code}})</option>
If the country code is equal to 46 i.e Sweden, the option will be selected.

Ref: Custom Helpers – Handlebars.js Tutorial