流星模板中的简单数据反射

Simple data reflection in meteor's template

本文关键字:简单 数据 反射 流星      更新时间:2023-09-26

我是流星的新手,对模板如何处理数据反射有一个很大的误解。例如,我在数据库中有一些数据,如下所示:

{name: {firstName: "foo",
lastName: "bar"},
father: "buz"}

我反映它的方式对我来说真的很可怕。我只能这样反映它:

Js:

var Products = new Meteor.Collection("Products");
if (Meteor.isClient) {
  Template.DataTry.dataTryArr = function(){
     return DataTry.find({father: "buz"});
  };
}

.html:

<head><title>...</title></head>
<body>{{>DataTry}}</body>
<template name="DataTry">
  {{#each dataTryArr}}
    <p>Mr. {{father}} has a son {{name.firstName}}. They are both {{name.lastName}}</p>
  {{/each}}
</template>

它正在工作和反思。但我无法理解{{#each}}以及为什么我需要dataTryArr!没有 dataTryArr{{#if dataTryArr}}Template.DataTry = function(){...} 等就无法正常工作,它没有任何工作方式,没有{{#each}}(在那里迭代什么?!

请帮助我了解如何以这种方式反映简单的数据

<head><title>...</title></head>
<body>{{>DataTry}}</body>
<template name="DataTry">
    <p>Mr. {{father}} has a son {{name.firstName}}. They are both {{name.lastName}}</p>
</template>

提前致谢

必须使用 {{#each}}{{#with}} 块帮助程序来循环访问从模板帮助程序返回的值。

如果模板帮助程序从集合中返回大量数据,则可能需要{{#each}}迭代器,以便在 DOM 中呈现返回的值。如果模板帮助程序返回单个对象,在这种情况下可以使用{{#with}}块。

你已经建议过这个:

<body>{{>DataTry}}</body>
<template name="DataTry">
    <p>Mr. {{father}} has a son {{name.firstName}}. They are both {{name.lastName}}</p>
</template>

这将不起作用,如果Template.DataTry.dataTryArr()返回对象数组,则{{#each}} shuold 将<p> ... </p>包含在块中。

<template name="DataTry">
  {{#each dataTryArr}}
    <p>Mr. {{father}} has a son {{name.firstName}}. They are both {{name.lastName}}</p>
  {{/each}}
</template>

简而言之,{{#each dataTryArr}}将调用 dataTryArr 方法并循环访问返回的值。