简体   繁体   中英

Can't iterate over collection and insert into template

I'm a beginner at Meteor, and am not able to do the simple task of iterating over a collection and printing a single attribute for each item to the template. I have autopublish turned on so I haven't written pub/sub functions. All the other components I've made so far work, so I'm pretty sure the problem is somewhere in the code below.

In HTML (note the comment)

  <template name="tags">
    <div class="tags">
            {{#each printTags }}
                    {{name}} <br>
            {{/each }}
            <!-- why is nothing showing up here? -->
    </div>
  <template>

In JS file

    if (Meteor.isClient) {

      Tags = new Mongo.Collection("tags")

      tags = Tags.find({}).fetch();

      Template.tags.helpers({
            printTags: tags
      });
    }

On the client, in Dev Tools

    Tags.find().fetch().forEach(function(tag){console.log(tag["name"])})
    1
    2
    3
    4
    5

The problem with your code is that your printTags helper is assigned to a variable ( tags ) holding the result of fetching the collection documents when the collection is not yet filled with data.

You must use a function so the expression will be reactively re-evaluated when data is available :

Template.tags.helpers({
  printTags: function(){
    return Tags.find();
  }
});

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