Search code examples
handlebars.jshelper

How to set {{#each }} iterate value from helper


Usually for a {{#each}} block, we can set the value directly in it like: {{#each users}}:

user: [
    {name: 'foo'},
    {name: 'bar'}
]

What I need to do is do be able to set the {{#each}} iteration value from a helper.

I have tried with this helper:

Handlebars.registerHelper('myHelper', function () {
  return new Handlebars.SafeString('users');
});

## also tested with:
Handlebars.registerHelper('myHelper', function () {
  return 'users';
});

and in my view:

{{#each (myHelper)}} # and {{#each myHelper}}
  <p>{{name}}</p>
{{/each}}

But nothing get shown.

I appreciate if anyone can give me some pointers. Thanks in advance!


Solution

  • You can use a built-in function called lookup in order to achieve what you are trying to achieve.

    Try:

    {{#each (lookup . (myHelper))}}
       {{name}}
    {{/each}}