Each according to the result of an auxiliary function?

At the helm, I 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 this 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 believe that it is looking for a variable in the context myHelper, not a function.

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

I use Node, Express and handlebars-express

+4
source share
1 answer

JavaScript functions have an object, so theoretically you can do this (not verified).

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

   // Execute context if it 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;
});
Run codeHide result

Then in your code ...

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

var context = {myHelper: myHelper};
var html    = template(context);
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1589371/


All Articles