For(of) last item

#1

Hi All,

When using a stache for(of) helper, is there a way to know when the current item is the last (or not the last) in the list?

Cheers
Rob

#2

If you’re iterating over an array, you can use scope.index to get the index of the current item, and compare that to the length of the list.

You could create a helper like this:

stache.addHelper("last", (index, length) => index === length - 1);

Then you can use this in your view:

    {{#for(item of itemsArray)}}
      <p {{#if( last(scope.index, itemsArray.length) )}}class="last"{{/if}}>{{item}}</p>
    {{/for}}
#3

Hi Kevin,
That’s genius, super simple and works like a charm!

Thanks
Rob

1 Like
#4

You could also do a minusOne helper and use it like:

{{# eq( scope.index, minusOne( itemsArray.length ) ) }}

Created an idea for making this even easier here: https://github.com/canjs/can-stache/issues/674