Search code examples
javascriptmeteorspacebars

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


I am working on a project with Meteor.js and have some issue with the use of Handlebar : I want to retrieve the last item of a collection , and display the field : text which have html in it :

here is my javascript code :

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

and in the html the handlebar {{#each}} is working but not the {{#with}} which is kind of weird seeing that there is only one item returned.

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

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

Do you have any kind of idea why that is ?


Solution

  • {{#each}} iterates over a collection cursor or an array of JS objects.

    {{#with}} just sets the current data context of whatever argument you pass to the block helper.

    If you want the {{#with}} block to work correctly, do not return an array from your helper (calling fetch on the cursor you obtained via Posts.find({},...); converts it into an array).

    Instead you should use Posts.findOne({},...); to only get the first matched result as a plain object.