【问题标题】:Handlebars.js: How to access parent index in nested each?Handlebars.js:如何在每个嵌套中访问父索引?
【发布时间】:2013-01-29 01:18:32
【问题描述】:

如何在每个循环中访问父 @index 值?

尝试了以下方法:

{{#each company}}
{{#each employee}}
  {{../@index}} // how to access company index here?
{{/each}}
{{/each}}

这会导致错误:

期待“ID”,得到“DATA”

【问题讨论】:

    标签: javascript handlebars.js


    【解决方案1】:

    这对我有用:

    {{#each company}}
    {{setIndex @index}}
    {{#each employee}}
      {{../index}}
    {{/each}}
    {{/each}}
    

    JS:

    Handlebars.registerHelper('setIndex', function(value){
        this.index = Number(value + 1); //I needed human readable index, not zero based
    });
    

    只要确保 company 对象没有 index 属性即可。

    【讨论】:

    • 遗憾的是,如果从模板渲染内部循环,这似乎不起作用:{{>my-template}} 产生Cannot read property 'index' of undefined。你知道解决方案吗?
    • @Lincoln 你可以试试这里的建议stackoverflow.com/a/18026063/271442 - 我选择了包含帮助方法。
    • 这是一个很棒的技巧。我将分享一个 jsfiddle 链接。谢谢!
    • 这是一个可扩展版本,允许您设置键/值对的哈希:jsfiddle.net/gfullam/Dc35g 使用子表达式的示例:{{set index=@index indexPlus1=(math @index "+" 1)}}
    【解决方案2】:

    注册一个 Helper 方法:

    Handlebars.registerHelper('eachWithIndex', function(cursor, options) {
        var fn = options.fn, inverse = options.inverse;
        var ret = "";
        var idx = -1;
        //console.log(cursor);
        cursor.forEach(function(item){
            idx++;
            console.log(item.index);
            item.index = idx;
            ret+=fn(item);
        });
        return ret;
    }); 
    

    车把模板:

    {{#eachWithIndex outer}}
      {{#each inner}}
       {{../index}} // access outer index like this. I used hanlebars V1.3.0
       {{index}} // access inner index
      {{/each}}
    {{/eachWithIndex}}
    

    【讨论】:

      【解决方案3】:

      示例中有语法错误。正确的语法是{{@../index}}

      我们正在研究如何在未来的语言版本中支持这些参数的自定义命名,以便更容易处理。 https://github.com/wycats/handlebars.js/issues/907

      【讨论】:

      • 标记为正确的答案仍然很有帮助,但这是问题的正确答案。
      • 哦,看起来这是第一个实际答案,我的错
      • 这在 ember v2.2.0 中不起作用。 @Andrew Toy 有正确答案。
      【解决方案4】:

      回答: {{@../index}}

      来自Handlebars docs(参见“每个”助手部分的底部):

      “嵌套的each 块可以通过深度路径访问交互变量。例如,要访问父索引,可以使用{{@../index}}。”

      注意:我使用的是 v1.3,所以它至少有那么旧。

      提醒:助手是您最后的最佳选择。 9/10 有更好的解决方案。

      【讨论】:

      • 这是实际答案
      • {{@key}} 旧版本也支持吗?
      【解决方案5】:

      Ember v2.2.0 中似乎有一种新语法。我在这里尝试了所有答案,但它们对我不起作用。

      我发现有效的是命名父循环的索引和子循环的索引。

      {{#each parents as |parent parentIndex|}}
          {{parentIndex}}
          {{#each children as |child childIndex|}}
              {{parentIndex}}
              {{childIndex}}
          {{/each}}
      {{/each}}
      

      【讨论】:

        猜你喜欢
        • 2013-03-16
        • 1970-01-01
        • 2015-09-09
        • 2013-01-20
        • 2018-02-10
        • 2023-04-07
        • 2017-03-10
        • 2018-10-03
        • 1970-01-01
        相关资源
        最近更新 更多