How to exit {{#each}} loop?

I’ve tried to create a global helper that ‘return false’ and call it on the template but it doesnt break the loop.
Any help on exiting the each loop before its end?
Thank you

How are you calling this global helper? Also, could you please a sample code of your global helper?

Template.registerHelper(‘exit’, function() {
return false
})

and then {{ exit }} just after my {{#each}}
Im now searching in Template.instance().view i i can access it from here.

I’m still not sure what you are trying to achieve here, So I’m assuming that you might want to exit the loop at some particular element.

I’d suggest doing something like this with your global register helper, where you can accept an element and check that element with some condition and decide weather to do something or not.

Very roughly :

Template.registerHelper('should_exit', function (item) {
  if (item.key === '') {
    return true;
  } else {
    return false
  }
})

Use #if block helper and check the result of your global helper.

{{#each item in items}}
  {{#if should_exit item}}
    <!-- do nothing -->
  {{else}}
    <!--print something...-->
  {{/if}}
{{/each}}

Another way would be to pass only elements that you want to display using filter or map methods into your template helper function. That way you don’t have to exit the loop mannuly.

items() {
 const result = Items.find();
 return result.filter((item) => /* some condition*/ )
}
1 Like