简体   繁体   中英

Populating template through router in Meteor

I have a Meteor app. I have created a collection Messages .

I am publishing the messages on the server with

Meteor.publish("messages", function () {
  return Messages.find({'isDeleted': {$ne : true}}, {sort: {createdAt: -1}});
});

I am routing with iron-router :

this.route('messages', {
  path: '/messages',
  template: 'messages',
  waitOn: function() {
    return Meteor.subscribe('messages');
  },
  data: function() {
    return Messages.find({}, {sort: {createdAt: -1}});
  }
});

With this function, I use data: ... but I still need to use a helper in messages.js to actually get the data:

Template.messages.helpers({
  messages: function() {
    return Messages.find({}, {sort: {createdAt: -1}});
  },
});

Now I am ready to use the messages in the template with

{{#each messages}}
  {{> message}}
{{/each}}

Am I doing it correct or could I avoid using the helper and just let the router populate the template with the data? It seems to me that what I do is quite redundant.

Whether or not you should use data from your router is a matter of taste. Let's assume you decide to use it...

  1. You can remove your helper. You are correct - it's redundant.
  2. The data context for your template is this so you can change your template code to:
{{#each this}}
  {{> message}}
{{/each}}

Alternatively, if you'd like to avoid using this in your template, just modify your data as follows:

data: function() {
  return {messages: Messages.find({}, {sort: {createdAt: -1}})};
}

And now you can keep your original template code:

{{#each messages}}
  {{> message}}
{{/each}}

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