4
votes

This something what I can't understand and can't solve it...

Short example.

Template helper:

Template.bookDetails.helpers({

  book: function() {        

    console.log("Current router :_id: " + Router.current().params._id);
    return Books.findOne(Router.current().params._id);

}

Some lines of template:

<template name="bookDetails">
   ...
   {{#with book}}
     Title: {{book.title}} <br>
     Author: {{book.author}} <br>
     ISBN: {{book.isbn}} <br>
     ...more...
   {{/with}}
   ...
</template>

And the question is: why do I see print console.log() as many times as call book.some_field in template?

Is it normal???

1
You should only be seeing the log once unless there is something else in your code that is changing your data context for that helper function. I.e. is your Router.current().params._id changing at all? Also... if you prefer, you can use {{title}} instead of {{book.title}} - Scalahansolo

1 Answers

2
votes

Yes this is normal because your code actually calls the book helper multiple times.

You have to replace your code with the following one to make things simpler :

{{#with book}}
  Title: {{title}} <br>
  Author: {{author}} <br>
  ISBN: {{isbn}} <br>
{{/with}}

The #with structure will set the current data context to the value returned by the helper and you can then access each property without referencing book.