Search code examples
node.jsexpresshandlebars.js

RegisterHelper does not work as expected in handlebars


Newbie to NodeJs and Handlebars. I am passing array of values to view and have written below helper to decide whether to include view all action button or not based on length of array. If length>1 I want to display action button else not. Below is what I've.

Handlebars.registerHelper("arrLength", function(array) {
     console.log(array.length>1); //logs proper true or false
     return array.length>1;
}

In view I've it as below:

{{#arrLength this.nArray}}<a class="clear blue" style="float:right;" href="javascript:void(0);">View all</a>{{/arrLength}}

But in view it is not getting displayed even though length is > 1. Any idea what am doing wrong here?


Solution

  • Got it. I needed to bind to the option, which is passed as parameter. Not sure though what is the significance.

    Handlebars.registerHelper("arrLength", function(array,options) {
       if(array.length>1)
            return options.fn(this);
       else
            return options.inverse(this);
    }