流星 - 模板。建立简单的目录

时间:2015-05-27 17:07:01

标签: meteor spacebars

我是流星新手,所以请不要因为愚蠢的问题而责怪我!我很想在谷歌和Meteor.docs找到答案,但我的愚蠢现在比我强。

我正在尝试从两个Collection中构建简单的产品目录。

Catalogs = new Mongo.collection('catalogs');
Products = new Mongo.collection('products');

我的目标 - 是实现这样的观点:

Vegetables     <-- #1 catalog
  *Tomato      <-- product from #1 catalog
  *Cucumber    <-- another product from #1 ctalog
Fruits         <-- #2 catalog
  *Apple
  *Pineapple
  *Banana

创建目录并使用父ID添加产品没有问题。但现在我坚持使用Meteor模板并且没有任何想法,如何展示嵌套在父母目录中的产品。 有时我会和Laravel做类似的事情,在这种情况下,我会用Laravel's Blade检查每件产品:

{{$catalog->name}}
    @foreach ($products as $product)
       @if ($catalog->id == $product->parentId)
         {{$product->name}}
       @endif
    @endforeach

我同意,也许这不是优雅的解决方案,但它对我有用。 但是在Meteor中,随着“数据上下文”的改变(如果我理解他们的角色权利),我无法掌握,如何做到这一点,如果我不能得到父或者属性。我相信它必须有清晰直接的解决方法,但我自己也看不到:(

拜托,你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

假设每个目录都有name且每个产品都有namecatalogId,这里的模板会将所有目录和产品显示为一系列列表:

<template name='catalogProducts'>
  {{#each catalogs}}
    <div class='catalog-name'>{{name}}</div>
    <ul>
      {{#each products}}
        <li>{{name}}</li>
      {{/each}}
    </ul>
  {{/each}}
</template>
Template.catalogProducts.helpers({
  catalogs: function() {
    // find all of the catalogs
    return Catalogs.find();
  },
  products: function() {
    // here the context is a catalog, so this._id is the id
    // of the current catalog - this finds all of its products
    return Products.find({catalogId: this._id});
  }
});

推荐阅读:A Guide to Meteor Templates & Data Contexts