2

I need access to next item in array while using foreach loop in handlebars.js.I've tried:

{{#each items}}
{{#ifEven @index}}
<p>{{this.description}} - {{../items.[@index+1].description}}</p>
{{/ifEven}}
{{/each}}

but it seems that's not working correctly.

4
  • This is going to break as soon as you reach the last item in the array. Why do you need to include the next item in the current one? Commented Aug 20, 2018 at 16:59
  • Because I'm displaying only even items. If next item is odd, I want to put it's description in current iteration. Commented Aug 20, 2018 at 17:03
  • 1
    In that case you are doing too much on your template. It is best if you prepare your array before rendering. Templates should have as few logic as possible to avoid weird, hard to debug and trace errors. Commented Aug 20, 2018 at 17:05
  • Sure, but I wanted to keep it in template file for some reasons. I just solved this issue by using helper. Commented Aug 20, 2018 at 17:10

1 Answer 1

2

I already solved it using helper:

hbs.registerHelper('nextItem', function (array, index, options) {
  return options.fn(array[index + 1]);
});

And .hbs template now looks like this:

{{#each items}}
{{#ifEven @index}}
<p>{{this.description}} - {{#nextItem ../items index}} {{description}} {{/nextItem}}</p>
{{/ifEven}}
{{/each}}

I know, that last element will not show, but this doesn't matter in my case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.