11
votes

I want to iterate over an enumerable and display a counter

<div template repeat="{{ name in names }}">
  ###. {{name}}
</div>

What should I put instead of ### so it shows the position of the name:

1. John Doe
2. Jane Doe
3. etc...
4

4 Answers

17
votes

Polymer now has the ability to do this:

<template repeat="{{fruit in fruits | enumerate}}">
  <li>You should try the {{fruit.value}}. It is number {{fruit.index}}.</li>
</template>

Example taken from https://github.com/sethladd/dart-polymer-dart-examples/blob/master/web/iterate_loop_index/my_example.html

7
votes

The other solutions do not work for me in Polymer 0.3.4 (anymore?), but there is documentation on templates, including indexing while looping over a collection:

<template repeat="{{ foo, i in foos }}">
  <template repeat="{{ value, j in foo }}">
    {{ i }}:{{ j }}. {{ value }}
  </template>
</template>
2
votes

It was available in web_ui but is not yet available in Polymer.

Web UI is the precursor to polymer.dart. Polymer.dart is almost at feature parity with Web UI. Below is a list of Web UI features that have not yet been implemented in polymer.dart:

Value of index variable available inside of loops

https://www.dartlang.org/polymer-dart/#web-ui-parity

Until then, you can use asMap on the list and iterate over the keys:

  <template repeat="{{i in names.asMap().keys)}}">
    <div>{{i}}: {{names[i]}}</div>
  </template>
0
votes

Not available yet, but you can use the quiver package as demonstrated in this SO answer:

https://stackoverflow.com/a/18165968/1713985