简体   繁体   English

铁路由器与流星显示数据到模板

[英]Iron router with Meteor display data to template

I am using iron router with Meteor (latest versions). 我正在使用带有Meteor的铁路由器(最新版本)。 I have a template: 我有一个模板:

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

and in lib/router.js : 并在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. 当我运行页面时,我看到这个JJJJJJJJJJJJ空页面,添加了测试,看它是模板加载。 In the Products collection are 2 items with name . 在Products系列中有两个name项目。 I can read (select), add, remove items for this collection via WEB browser console, but the collection is not rendered in the template. 我可以通过WEB浏览器控制台读取(选择),添加,删除此集合的项目,但该集合不会在模板中呈现。 What can be the error ? 可能是什么错误?

The data function of Iron Router sets the data context for the template. Iron Router的data功能设置模板的数据上下文 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. 在您的情况下,您将数据上下文设置为游标,但尝试使用不作为帮助程序存在的products访问游标,无论是全局注册还是模板本身注册。

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: 或者,您可以在模板中使用this关键字来访问当前数据上下文:

<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除非你可以通过对模板的路线遵循的数据流。 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 : 解决方案是在lib/router.js ,需要像这样设置属性data

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

, NOT like before - return Products.find(); ,不像以前那样 - return Products.find(); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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