Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With a template how to use {{attribute}} with one 'record' compared to #each using a find() cursor?

Tags:

meteor

I know using a Template you can display multiple documents with their attributes like:

// html
<template name="hello">
{{#each greetings}}
   {{message}}
{{/each}}
</template>

// js
Template.hello.greetings = function() {
   return Greetings.find();
}

Which shows Greeting.message for each greeting found document.

My question is how to use this template for only one document? (incl. no available document)

From javascript side I would use something like return Greetings.findOne({'id' : Session.get("greeting_id")});

But when using the template:

<template name="hello">
   {{message}}
</template>

an error is thrown: Uncaught TypeError: Cannot read property 'message' of undefined

UPDATE

For now I use this on JS side, using the template as suggested by @tom-wijsman below:

Template.hello.greeting = function() {
   var greeting = Greetings.findOne({'id' : Session.get("greeting_id")})
   if (greeting)
       return greeting;
   return {message: ""};
}
like image 644
Michel Löhr Avatar asked May 15 '12 12:05

Michel Löhr


1 Answers

Handlebars.js also has a #with helper.

<template name="hello">
    {{#with greeting}}
        {{message}}
    {{/with greeting}}
</template>

 

Template.hello.greeting = function() {
    return Greetings.findOne({'id' : Session.get("greeting_id")});
}
like image 109
Tamara Wijsman Avatar answered Sep 20 '22 22:09

Tamara Wijsman