11

why doesn't this work in meteor? https://github.com/wycats/handlebars.js/issues/250

afhammad
  • 287
  • 1
  • 3
  • 9
  • See a good answer here: [http://stackoverflow.com/questions/13329898/is-there-a-way-to-get-index-while-iterating-through-collection-in-meteor][1] [1]: http://stackoverflow.com/questions/13329898/is-there-a-way-to-get-index-while-iterating-through-collection-in-meteor – zorlak Dec 14 '12 at 00:55

3 Answers3

9

It's not yet implemented in meteor's version of handlebars; there's a subtlety about the reactivity of @index rendering properly. You can read more about it here: https://github.com/meteor/meteor/issues/489#issuecomment-11270564

Tom Coleman
  • 3,037
  • 18
  • 16
9

This is definitely a frustration for me as well. In the meantime I made a handlebars helper to parse anything into named 'key' and 'value' objects:

Handlebars.registerHelper('key_value', function(context, options) {
  var result = [];
  _.each(context, function(value, key, list){
    result.push({key:key, value:value});
  })
  return result;
});

This would be used with the #each operator like:

<dl class="attributes">
  {{#each key_value attributes}}
    <dt>{{key}}</dt><dd>{{value}}</dd>
  {{/each}}
</dl>
Mike Marcacci
  • 1,913
  • 1
  • 18
  • 24
  • 2
    This works perfectly. I used this with a little modification. I simply add a `_key` field to the `value` and push `value` directly to the results. – Arunoda Susiripala Oct 28 '13 at 05:06
6

Another way to get it to work is to use a standard Meteor template helper with the map cursor function.

Here's an example showing how to return the index when using each with a collection:

index.html:

<template name="print_collection_indices">
  {{#each items}}
    index: {{ this.index }}
  {{/each}}

index.js:

Items = new Meteor.Collection('items');

Template.print_collection_indices.items = function() {
  var items = Items.find().map(function(doc, index, cursor) {
    var i = _.extend(doc, {index: index});
    return i;
  });
  return items;
};
davidd8
  • 183
  • 2
  • 4