简体   繁体   English

如何在每个循环中获取 Meteor 模板中数组的索引?

[英]How can I get the index of an array in a Meteor template each loop?

Say I have an object, someObject:假设我有一个对象,someObject:

{
  foo: "apple",
  myArray: ["abc", "def"]
}

And a template helper that looks like this (and works fine):和一个看起来像这样的模板助手(并且工作正常):

getArray: function(){
  var self = this;
  self.myArray = self.myArray || [];    
  return self.myArray;
}

How should I construct the html to get the array index?我应该如何构造 html 来获取数组索引?

I've tried:我试过了:

<template name="someObject"> // takes someObject as data
  {{#each getArray}}
    <div class="item" data-value="{{WHAT GOES HERE?}}">{{this}}</div>
  {{/each}}
</template>

In which case this successfully returns "abc" and "def" .在这种情况下, this成功返回"abc""def" Which is good.哪个好。 But how can I get the index of the array to put into the attribute data-value ?但是如何获取数组的索引以放入属性data-value

I've tried this.index directly but it's undefined.我已经直接尝试过this.index但它是未定义的。 I also tried using a helper:我也尝试使用助手:

<template name="someObject"> // takes someObject as data
  {{#each getArray}}
    <div class="item" data-value="{{getindex}}">{{this}}</div>
  {{/each}}
</template>

but in this helper getIndex when I console.log out this I see:但在这个帮手getIndex当我CONSOLE.LOG了this我见:

String {0: "a", 1: "b", 2: "c", length: 3}
String {0: "d", 1: "e", 2: "f", length: 3}

Is it possible to get the index?是否可以获取索引?

meteor >= 1.2流星 >= 1.2

Spacebars gained a lot of functionality in 1.2, including a native @index .空格键在 1.2 中获得了很多功能,包括原生的@index Helpers are no longer needed to solve this problem - you can simply do this:不再需要助手来解决这个问题——你可以简单地这样做:

{{#each getArray}}
  <div class="item" data-value="{{@index}}">{{this}}</div>
{{/each}}

or, if you want to use the index inside a helper:或者,如果您想在助手中使用索引:

{{#each getArray}}
  <div class="item" data-value="{{someHelper @index}}">{{this}}</div>
{{/each}}

meteor < 1.2流星 < 1.2

Sometime in the future, spacebars may offer the ability to determine the index directly in the template.将来的某个时候,空格键可能会提供直接在模板中确定索引的能力。 However, as of this writing, the only way to get the index is to modify the result returned by the helper.但是,在撰写本文时,获取索引的唯一方法是修改助手返回的结果。 For example you could have getArray return an array of objects which contain a value and an index , like this:例如,您可以让getArray返回一个包含valueindex的对象数组,如下所示:

getArray: function() {
  var self = this;
  self.myArray = self.myArray || [];
  return _.map(self.myArray, function(value, index){
    return {value: value, index: index};
  });
}

And the template could use the index like this:模板可以像这样使用索引:

<template name="someObject">
  {{#each getArray}}
    <div class="item" data-value="{{index}}">{{value}}</div>
  {{/each}}
</template>

Also see this answer for a similar example with cursors.有关游标的类似示例,另请参阅此答案

It's worth mentioning that you probably don't need to store the index in the DOM itself via data-value , unless it's needed by an external plugin.值得一提的是,您可能不需要通过data-value将索引存储在 DOM 本身中,除非外部插件需要它。 As you can see in the example below, each item has a context with an index value.正如您在下面的示例中看到的,每个item都有一个带有索引值的上下文。 For more information, see this blog post .有关更多信息,请参阅此博客文章

Template.someObject.events({
  'click .item': function() {
    console.log(this.index);
  }
});

You can make this a reusable helper, too.你也可以把它变成一个可重用的助手。 It's handy to have:很方便:

JS: JS:

UI.registerHelper('addIndex', function (all) {
    return _.map(all, function(val, index) {
        return {index: index, value: val};
    });
});

HTML: HTML:

{{#each addIndex somearray}}
<div>
   {{index}}: {{value}}
</div>
{{/each}}

This change is coming and you will be able to do {{@index}} .此更改即将到来,您将能够执行{{@index}} When meteor supports the most recent version of handlebars.当meteor 支持最新版本的把手时。

您可以更改 getArray 以返回元组数组并将索引存储在那里。

Here is an example of how you can just add index to the object and as long as you didnt have a key named index before it shouldnt obstruct anything this way works only with arrays of objects.这是一个示例,说明如何向对象添加索引,并且只要您没有名为 index 的键,它就不应该以这种方式仅对对象数组起作用。 Now if you have a array of values you should use Christan Fritz answer现在,如果您有一组值,则应使用 Christan Fritz 的答案

UI.registerHelper("withIndex", function(obj) {
  obj = obj || [];
  _.each(obj, function (object, index) {
    obj[index].index = index;
  });
  return obj;
});

{#each withIndex fields}}
   <div class="form-group field" data-index="{{index}}">
      <label for="{{name}}">{{title}}</label> 
    </div>
{{/each}}

You can do it with underscore too, assuming that you have subscribed your template to array of objects您也可以使用下划线来完成,假设您已将模板订阅到对象数组

Template.yourTemplate.helpers({
  objectsWithIndex: function() {
    _.map(this.objects, function(value, key) {
      return _.extend(value, {
        index: key
      });
    });
    return this.objects;
  }
});

and in your html...并在您的 html 中...

<template name="someObject">
  {{#each objectsWithIndex}}
    <div class="item" data-value="{{index}}">{{value}}</div>
  {{/each}}
</template>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何循环遍历 object 并获取每个元素的索引并将其存储在数组中? - How can I loop through an object and get the index of each element and store it in an array? 在流星中遍历数组时如何获取模板详细信息 - How do I get template details when traversing an array in Meteor 如何遍历一个jQuery数组,然后一次输出一项(从索引0开始)? - How can I loop through a jquery array and then output each item (starting at index 0) one at a time? 如何用forEach替换javascript for循环并获取每次迭代的索引? - How can I replace a javascript for loop with a forEach and get access to the index for each iteration? 如何使用 javascript 中的每个循环获取当前索引并更新到实时数据库 - How can i get current Index using for each loop in javascript and update into realtime database 是否可以每次在Meteor模板中使用唯一变量? - Can I use a unique variable in Meteor template each time? 如何调用流星模板事件? - How can I call a Meteor template event? 如何在流星模板上使用if条件? - How can I use if condition on the meteor template? 我怎样才能获得所有数组索引 - How can i get all index of array 在Meteor中,我如何编写一个帮手来在车把的每个循环中使用? - In Meteor, how can I write a helper to use in the handlebar's each loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM