2

According to this question, it was possible to do something like this with Handlebars rc1:

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

{{@index}} would basically give you the iteration index, which is really useful when creating tables.

When I try this with Ember.js rc3, I get an unexpected token error. Does this not work anymore? Did it ever work? Is there another way to get the iteration index?

4

3 回答 3

1

看起来这是可能的。无法让它与 HBS RC3 一起使用。可能,已弃用。

这是一个“手写”的HBS 助手

于 2013-04-30T05:20:58.697 回答
1

这可以帮助您使用 {{index}} 获取索引,并且您可以并排了解迭代是否分别使用 {{first}} 和 {{last}} 在数组的第一个或最后一个对象上进行。

Ember.Handlebars.registerHelper("foreach", function(path, options) {
   var ctx;
    var helperName = 'foreach';

    if (arguments.length === 4) {
        Ember.assert("If you pass more than one argument to the foreach helper, it must be in the form #foreach foo in bar", arguments[1] === "in");

        var keywordName = arguments[0];


        options = arguments[3];
        path = arguments[2];

        helperName += ' ' + keywordName + ' in ' + path;

        if (path === '') {
            path = "this";
        }

        options.hash.keyword = keywordName;

    } else if (arguments.length === 1) {
        options = path;
        path = 'this';
    } else {
        helperName += ' ' + path;
    }

    options.hash.dataSourceBinding = path;
    // Set up emptyView as a metamorph with no tag
    //options.hash.emptyViewClass = Ember._MetamorphView;

    // can't rely on this default behavior when use strict
    ctx = this || window;
    var len = options.contexts[0][path].length;
    options.helperName = options.helperName || helperName;
    options.contexts[0][path].map(function(item, index) {
        item.index = index;
        item.first = index === 0;
        item.last = index === len - 1;
    })
    if (options.data.insideGroup && !options.hash.groupedRows && !options.hash.itemViewClass) {
        new GroupedEach(ctx, path, options).render();
    } else {
        return Ember.Handlebars.helpers.collection.call(ctx, Ember.Handlebars.EachView, options);
    }
});

这可以像这样测试

{{#foreach array}}
    {{log index first last}}
{{/foreach}}
于 2015-08-20T11:29:20.103 回答
0

我最近遇到了同样的问题,我通过编写绑定助手并通过绑定传递对象来完成,例如这里的项目是一个 ember DS.Store 对象,内容是控制器的“内容”。希望它

Ember.Handlebars.registerBoundHelper 'isPair', (content, options)->
  item =  options.hash.item
  content_name = options.hash.content || 'content'
  if @get(content_name).indexOf(item) % 2 == 0 then 'is-pair' else 'is-unpair'

在你看来你称之为

{{isPair content itemBinding='order'}}

我不知道它是否是您正在寻找的东西,但它可能会给您一些想法,如何在您的项目中使用它。

顺便提一句。Ember 覆盖了#each 助手,这就是我想没有@index 的原因

于 2013-05-01T08:18:34.150 回答