简体   繁体   中英

Meteor: How can I use Spacebars to create a tree list with data from two collections?

Lets say I have two collections. One for Categories and one for Items .

Categories looks like this...

{
    _id: "1",
    catName: "Category One"
}
{
    _id: "2",
    catName: "Category Two"
}

And Items looks like this...

{
    _id: "12",
    itemName: "Item One",
    category: "1"
}
{
    _id: "13",
    itemName: "Item Two"
    category: "2"
}
{
    _id: "14",
    itemName: "Item Three"
    category: "1"
}

How can I use spacebars to create a tree list with the appropriate Items beneath each Category?

For example, something like this...

HTML

<div class="panel-group">
   <div class="panel panel-default">

   {{#each category}}

     <div class="panel-heading">
       <a data-toggle="collapse" href="#collapse1">{{catName}}</a>
     </div>

     {{#if itemsInThisCategory}}
       <div id="collapse1" class="panel-collapse collapse">

         {{#each item}}
           <div class="panel-body">{{itemName}}</div>
         {{/each}}

       </div>
     {{/if}}

   {{/each}}

   </div>
</div>

How would the helpers be done for this? Or is it even possible to do it this way? Because I think I am trying to access different data contexts within the same each statement and I am not sure this will work.

Thanks

Helpers:

Template.myTemplate.helpers({
  categories: function() {
    return Categories.find({});
  },
  hasItemsInCategory: function(category) {
    return Items.find({
      category: category
    }).count();
  },
  getItemByCategory: function(category) {
    return Items.find({
      category: category
    });
  }
});

Template:

<template name="myTemplate">
  <div class="panel-group">
    <div class="panel panel-default">
      {{#each categories}}
        <div class="panel-heading"><a data-toggle="collapse" href="#collapse1">{{catName}}</a>
          {{#if hasItemsInCategory _id}}
            <div id="collapse1" class="panel-collapse collapse">
              {{#each getItemByCategory _id}}
                <div class="panel-body">{{itemName}}</div>
              {{/each}}
            </div>
          {{/if}}
        </div>
      {{/each}}
    </div>
  </div>
</template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM