time

How to enumerate array/cursor in template with comma in MeteorJS

If you want to enumerate array/cursor in MeteorJS with comma you can use $mapped from handlebar-helpers.

Install

meteor add raix:handlebar-helpers

Prepare items for template

Template.movies.helpers({
    movies: function() {
        return Movie.find();
    }
})

$mapped will map $first, $last, and $index onto your cursor or array

<template name="movies">
Favoured movies:

{{#each $mapped movies}}
    {{title}}{{#unless $last}},{{/unless}}
{{/each}}
</template>

Or we can write custom global helper (without external lib in CoffeeScript). You get access to index, item, is first, is last or is even. Put it somewhere in lib directory of project, for example, helpers.coffee file.

Template.registerHelper 'mapped', (arr) ->
    arr = arr.fetch() || []
    out = []
    _.each(arr, (item, indx) ->
        i = indx + 1
        out.push({
            index: i,
            item: item,
            first: i == 1,
            last: i == arr.length,
            even: i % 2 == 0
        })
    )
    return out    

Usage

<template name="movies">
Favoured movies:

{{#each mapped movies}}
    {{item.title}}{{#unless $last}},{{/unless}}
{{/each}}
</template>
comments powered by Disqus