Generating a loop counter in Ember.js #each

夙愿已清 提交于 2019-12-02 03:33:13

问题


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.)



来源:https://stackoverflow.com/questions/12331780/generating-a-loop-counter-in-ember-js-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!