Question

Say I've got a repeating template:

<template bind repeat id='my-template'>
    This is the bound value: <span id="#myid[x]"> {{}} </span>
</template>

what can I replace [x] with that will be unique? Access to the loop counter would do the trick, but I'm open to suggestions.

Was it helpful?

Solution

I'm adding some utilities to Fancy Syntax (Polymer.dart's default binding syntax now) to help with this, but the basic outline is to run your collection though a filter that will add indices and return a new Iterable.

Here's some code that will do it now though:

import 'package:fancy_syntax/fancy_syntax.dart';
import 'package:mdv/mdv.dart';

Iterable<IndexedValue> enumerate(Iterable iterable) {
  int i = 0;
  return iterable.map((e) => new IndexedValue(i++, e));
}

class IndexedValue<V> {
  final int index;
  final V value;

  IndexedValue(this.index, this.value);
}

main() {
  query('#my-template')
    ..bindingDelegate = new FancySyntax(globals: {
      'enumerate': enumerate,
    })
    ..model = ['A', 'B', 'C'];
}
<template bind id='my-template'>
  <template repeat="{{ item in this | enumerate }}">
    This is the bound value: <span id="#myid-{{ item.index }}">{{ item.value }}</span>
  </template>
</template>

I'm trying to get a bunch of utilities like Python's itertools into a library for uses like this. I'll update when they're available.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top