googlearchive / TemplateBinding

TemplateBinding Prolyfill
290 stars 61 forks source link

template instances can't access their index position within the iteration #117

Closed rafaelw closed 10 years ago

rafaelw commented 11 years ago

e.g. <template repeat="{{ items }}">{{ _index }}</template>

cc @ebidel

faassen commented 11 years ago

Just to throw a possibility into the hat. The approach I've used in Obviel Template (inspired by TAL templates) is to introduce a special "@repeat" variable, prefixed with @ to avoid name clashes.

@repeat.index gives you the index, @repeat.number is index + 1 (useful for UIs), I also have @repeat.length for the length of the array, and @repeat.first and @repeat.last are also useful (true only if at the beginning or end of the array).

If you have multiple scopes and want to explicitly refer to the index of the outer scope, I allow @repeat.outer.index. What happens when you have a scope called 'index'? I think I have this override the proper index, as you can always access the actual index using the full notation (@repeat.index.index, in this case).

Of course, @ would be a problem if you want the expression syntax to remain a subset of JS. You could avoid nameclashes by using a special object that is at least rare in JS.

aeosynth commented 10 years ago

+1

gavindoughtie commented 10 years ago

+1 (my example is a fan of playing cards, where each one has a slightly different rotation value)

rafaelw commented 10 years ago

Fixed: https://github.com/Polymer/polymer-expressions/commit/b1fc58f9ea86958d146a587ef02e1ba63625e252

e.g.

<template repeat="{{ user, userIndex in users }}">
  Index Position: {{ userIndex }}, Username: {{ user.name }}
</template>