【问题标题】:Why Does {{#each}} Work Properly While {{#with}} Does Not?为什么 {{#each}} 能正常工作而 {{#with}} 不能?
【发布时间】:2015-04-29 05:21:55
【问题描述】:

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

这是我的 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}}

你知道为什么会这样吗?

【问题讨论】:

    标签: javascript meteor spacebars


    【解决方案1】:

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

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

    如果您希望{{#with}} 块正常工作,请不要从帮助程序返回数组(在您通过Posts.find({},...); 获得的光标上调用 fetch 会将其转换为数组)。

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

    【讨论】:

    • 非常感谢,它帮助我理解了我遇到的另外两个错误!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 2019-01-04
    • 2020-09-03
    • 2016-10-10
    • 2016-10-24
    • 2017-02-27
    • 2017-07-08
    相关资源
    最近更新 更多