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

Time:12-28

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.

CodePudding user response:

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!

CodePudding user response:

Meteor uses the Spacebars templating language. According to the documentation, you should prefer the newer each ... in syntax instead of the older each syntax.

Both support the special @index variable that you can use to easily identify the first element in the sequence. Knowing the first element, you can add a comma before every output except for the first iteration:

{{#each record in records}}{{#unless @index}} ,{{/unless}}{{record}}{{/each}}

The supported unless block works the same as an if block just with an inverted condition check.

Notice that I use double braces instead of triple-places to support escaping of special characters and prevent html injection attacks.

  • Related