【问题标题】:Meteor JS: How to use Spacebars to display contents inside an array retrieved from Meteor CollectionMeteor JS:如何使用空格键显示从 Meteor Collection 检索到的数组中的内容
【发布时间】:2015-07-03 02:08:35
【问题描述】:

我有一个收藏:

MenuItems = new Mongo.Collection('menu_items');

我还有一个数组:

var arrayToInsert = ['Gemstone', 'Rings'];

然后我通过以下方式将该数组插入到集合中:

MenuItems.insert(arrayToInsert);

在我的 mongodb 中生成的文档如 RoboMongo 所示:

{
    "_id" : "yRXmFGxLCZXLf9Ynh",
    "0" : "Gemstone",
    "1" : "Rings"
}

在我的模板助手中,我有:

menuItems: function(){
    return MenuItems.find();
  },

在我的 .html 文件中,我这样做:

{{#each menuItems}}
  {{this}}
{{/each}}

但我只得到这个输出:

[object Object]

如何使用空格键遍历这个数据数组,以便我可以让它显示“宝石”和“戒指”????

非常感谢。

【问题讨论】:

  • 嗨,{{this[1]}} 不起作用....{{this[0]}} 也不起作用....
  • 哎呀它的 {{this.[1]}} 忘记了结果是一个对象数组

标签: javascript mongodb meteor spacebars


【解决方案1】:

如果你想让数组代表菜单项的值,你应该像这样将它们插入到集合中:

arrayToInsert.forEach(function(menuItem){
  MenuItems.insert({
    label: menuItem
  });
});

然后您可以在模板中显示菜单项:

JS

Template.menu.helpers(function(){
  menuItems: function(){
    return MenuItems.find();
  }
});

HTML

<template name="menu">
  <ul>
    {{#each menuItems}}
      <li>{{label}}</li>
    {{/each}}
  </ul>
</template>

如果要将数组存储为集合文档的一部分,请使用以下代码:

JS

MenuItems.insert({
  items:arrayToInsert
});

HTML

<template name="menu">
  {{#each menuItems}}
    <ul>
      {{#each items}}
        <li>{{this}}</li>
      {{/each}}
    </ul>
  {{/each}}
</template>

【讨论】:

  • 好的,所以使用它当前的插入形式,例如MenuItems.insert(arrayToInsert);没有办法使用空格键显示数据???它真的必须像上面的例子一样分配给一个“键”???谢谢
  • 将数组分配给一个键更容易操作,您不必处理this.[index] 语法。
猜你喜欢
  • 2013-07-28
  • 2016-01-26
  • 1970-01-01
  • 1970-01-01
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
  • 2016-12-24
  • 2015-03-17
相关资源
最近更新 更多