为什么 {{#each}} 可以正常工作而 {{#with}} 不能?

Why Does {{#each}} Work Properly While {{#with}} Does Not?

我正在使用 Meteor.js 开发一个项目,在使用 Handlebar 时遇到一些问题:我想检索集合的最后一项,并显示字段:包含 [=21= 的文本] 其中:

这是我的 javascript 代码:

Template.postVerif.helpers({
  'lastPost' :function(){
    lastPost = Posts.find({}, {sort:{timestamp:-1}, limit :1}).fetch();
       return lastPost
  }
})

并且在 html 车把 {{#each}} 工作但 {{#with}} 不工作 看到只有一件商品返回,这有点奇怪。

{{#each lastPost}}  
    {{{text}}}
{{/each}}

 {{#with lastPost}}
    {{{text}}}
 {{/with}}

你知道这是为什么吗?

{{#each}} 遍历集合游标或 JS 对象数组。

{{#with}} 只是设置您传递给块助手的任何参数的当前数据上下文。

如果您希望 {{#with}} 块正常工作,请不要 return 来自您的助手的数组(对您通过 Posts.find({},...); 获得的游标调用 fetch 将其转换为数组).

相反,您应该使用 Posts.findOne({},...); 仅将第一个匹配结果作为普通对象。