mikedavies-dev
mikedavies-dev

Reputation: 3355

each over the result of a helper function?

In handlebars I have registered a helper function that returns a list, for example:

function myHelper() {
    return [
        'some val 1',
        'some val 2',
        'some val 3'
    ]
}

I would like to call that function and iterate over the results using Handlebars, something like this:

{{#each myHelper}}
<li>{{this}}</li>
{{/each}}

However this does not call my function, I presume it is looking for a variable in the context called myHelper and not the function.

Is there a way to do this or do I need to add the result of myHelper() to the context as a variable before the page is rendered?

I'm using Node, Express and handlebars-express

Upvotes: 4

Views: 67

Answers (1)

SharpEdge
SharpEdge

Reputation: 1762

In JavaScript functions are object so in theory you could do this (is not tested).

Handlebars.registerHelper('each', function(context, options) {

   // Execute context if it's a function to get the array
   if(typeof context == "function")
     context = context();
  
  var ret;
  
  for(var i=0, j=context.length; i<j; i++) {
    ret += options.fn(context[i]);
  }

  return ret;
});

Then in your code...

function myHelper() {
    return [
        'some val 1',
        'some val 2',
        'some val 3'
    ]
}

var context = {myHelper: myHelper};
var html    = template(context);

Upvotes: 1

Related Questions