通过Meteor中的路由器填充模板

时间:2022-11-04 19:41:17

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

我有一个流星应用程序。我创建了一个集合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:

使用此函数,我使用数据:...但我仍然需要在messages.js中使用帮助器来实际获取数据:

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.

我这样做是正确的还是我可以避免使用帮助器,让路由器用数据填充模板?在我看来,我做的事情是多余的。

1 个解决方案

#1


2  

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. 你可以删除你的助手。你是对的 - 这是多余的。

  3. The data context for your template is this so you can change your template code to:
  4. 您的模板的数据上下文是这样的,因此您可以将模板代码更改为:

{{#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}}

#1


2  

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. 你可以删除你的助手。你是对的 - 这是多余的。

  3. The data context for your template is this so you can change your template code to:
  4. 您的模板的数据上下文是这样的,因此您可以将模板代码更改为:

{{#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}}