简体   繁体   中英

Iron router with Meteor display data to template

I am using iron router with Meteor (latest versions). I have a template:

<template name="home">
    {{#each products}}
        <p>{{name}}</p>
    {{/each}}
    JJJJJJJJJJJJ
</template>

and in lib/router.js :

Router.configure({
   layoutTemplate:'layout'
});

Router.map(function () {
   this.route('home', {
   path:'/',
   template:'home',
   data : function () {
              return Products.find();
          }
   });
});

When I run the page, I see empty page with this JJJJJJJJJJJJ , added for test to see is it template loads. In the Products collection are 2 items with name . I can read (select), add, remove items for this collection via WEB browser console, but the collection is not rendered in the template. What can be the error ?

The data function of Iron Router sets the data context for the template. In your case, you are setting the data context to be a cursor but attempting to access the cursor with products , which does not exist as a helper, either registered globally or on the template itself.

There's a few ways you can fix this, but I would suggest letting the router simply determine which template to render and let the template fetch it's own data.

Adjusted router:

Router.map(function () {
  this.route('home', {
    path: '/',
    template: 'home'
  }
);

Template helper:

Template.home.helpers({
  products() {
    return Products.find();
  }
});

Alternatively, you can use the this keyword within the template to access the current data context:

<template name="home">
  {{#each this}}
    <p>{{name}}</p>
  {{/each}}
  JJJJJJJJJJJJ
</template>

However, it is not easy to discern what is being put into this unless you can follow the flow of the data through the route to the template. This also couples this template very tightly with this route, as the route itself is determining the context of your template.

The solution is in lib/router.js , need to set attribute data like this :

data : function () {
           templateData = {
               products: Products.find()
           };
           return templateData;
       }

, NOT like before - return Products.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