Search code examples
javascripthtmlmeteor

How to decide within #each that the element is the last?


I have a simple code like this:

{{#each records}} {{{this}}}, {{/each}}

I would like to produce an output like A, B, C, D - no comma after the last element (currently, there is one indeed). So I would need to determine within the cycle when an element is the last one, or something like that. I was thinking about a helper function but as the function would not know what element is being iterated, I cannot see how that would work.


Solution

  • You rather should process the list outside of the render and just display the result:

    const list = ['A', 'B', 'C', 'D']
    
    Template.myTemplate.onCreated(function () {
      this.list = new ReactiveVar()
      this.list.set(list.join(','))
    })
    
    Template.myTemplate.helpers({
      list () {
        return Template.instance().list.get()
      }
    })
    
    {{list}}
    

    Which will be A, B, C, D

    Additionally, if you use three brackets {{{expression}}} then you render directly to the DOM so use this with care!