Generating a loop counter in Ember.js #each

2019-02-26 12:06发布

问题:

I'm finding the restrictions of handlebar templates in Ember.js to be absolutely crippling. You can't execute arbitrary javascript. All you get is a fixed set of abilities (if/else, each, action, view, outlet) and the ability to output the value of a property on the current context object.

Which means I cannot figure out how to do something as simple as utilizing a loop counter in order to, for example, slap positional IDs on an html element inside a loop based on it's position in the collection I'm iterating on.

It doesn't make sense to add it as a computed property on the model, because that's not model-level knowledge (the same model could be in two different positions in different views).

FYI-Using Ember-1.0-pre, Ember-Data, and Rails with ActiveModel::Serializers on PostgreSQL.

回答1:

I'd recommend writing a handlebars helper, in which you can execute arbitrary javascript. See http://handlebarsjs.com for some examples.

Alternatively, you could include the positional IDs on your child views (not your models).



回答2:

With handlebars.js (v. 1.0.rc1) I could do this:

 {{#each links}}
   <li>{{@index}} - {{url}}</li>
 {{/each}}


回答3:

Turns out providing a loop counter is the exact subject of the final example on this page:

http://handlebarsjs.com/block_helpers.html

(Dan G already pointed out the "writing a helper" solution in his answer, but since there's already a published example, I wanted to create a fresh answer to make the link more prominent.)