【问题标题】:Multiple each index on Meteor Blaze多个 Meteor Blaze 上的每个索引
【发布时间】:2016-05-07 12:03:27
【问题描述】:

我正在使用来自 Meteor 的 Blaze 作为 html 模板,并且我有多个循环,例如:

let objects = [{name: 'John', age: 18}, {name: 'Foo', age: 25}, {name: 'Bar', age: 35}]
let attrs = ['name', 'age']


{{#each objects}}
  <h3>Object {{@index}}</h3>
  {{#each attrs}}
    [...] // code here
  {{/each}}
{{/each}}

我知道:

  • {{@index}} 用于了解当前循环索引(因此 [..] {{@index}} 是 attrs 数组上索引的引用
  • {{this}} 用于知道当前循环值(如[...] {{value}}nameage
  • {{..}} 是对父循环值的引用(因此 [...] {{..}} 是当前对象,在第一个循环中)

现在,我想在[...] 上为objects 循环当前的索引。我在 Google 和 Stackoverflow 上搜索了很多,但没有找到。

【问题讨论】:

    标签: javascript meteor each meteor-blaze


    【解决方案1】:

    Huumm,关于 Blaze 的新闻允许新创建变量(使用#let)。一个简单的解决方案是:

    let objects = [{name: 'John', age: 18}, {name: 'Foo', age: 25}, {name: 'Bar', age: 35}]
    let attrs = ['name', 'age']
    
    
    {{#each objects}}
      {{#let object=this object_idx=@index}}
        <h3>Object {{object_idx}}</h3>
    
        {{#each attrs}}
          Object idx {{object_idx}} | Object {{object}}
          Attr idx {{@index}} | Attr {{this}}
        {{/each}}
    
      {{/let}}
    {{/each}} 
    

    更新:你甚至可以做一段时间{{#each object in objects}},避免你做{{#let object=this}}

    {{#each object in objects}}
      {{#let object_idx=@index}}
        <h3>Object {{object_idx}}</h3>
    
        {{#each attr in attrs}}
          Object idx {{object_idx}} | Object {{object}}
          Attr idx {{@index}} | Attr {{attr}}
        {{/each}}
    
      {{/let}}
    {{/each}} 
    

    【讨论】:

    • #let 关键字使拥抱变得可用。
    【解决方案2】:

    您需要为内部循环创建一个助手,如下所示:

    Template.myTemplate.helpers({
      value: function(){
        return Template.parentData(1)[this];
      }
    });
    

    Template.parentData(1) 返回从当前级别向上一 (1) 级的数据上下文。 [this] 引用当前数据给出的那个对象的键。

    【讨论】:

    • 我要索引!不是价值
    • 啊,对不起。我不知道获取父上下文的索引是可能的。我建议您使用来自this answer 的@David Weldon 模式将一个索引变量映射 到您的外部对象数组中
    猜你喜欢
    • 2016-03-17
    • 2014-11-06
    • 2014-09-04
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 2017-01-10
    • 2019-01-20
    • 2022-07-10
    相关资源
    最近更新 更多