[Updated] Basic Template Level Subscription Usage

UPDATE

is this the right way to do?

Template.post.onCreated(function(){
	var self = this;
	  self.autorun(function () {
	    self.subscribe('post', Router.current().params._id);
	});
});

Template.post.helpers({
	post: function(){
		return Posts.findOne(Router.current().params._id);
	}
});

and on template file

<template name="post">

	{{#if Template.subscriptionsReady}}
	    <!-- This is displayed when all data is ready. -->
	    <h1>{{post.title}}</h1>
	    <p>
	    	{{post.body}}
	    </p>
	  {{else}}
	    Loading...
	{{/if}}
</template>

and publish function

Meteor.publish('posts', function(){
	return Posts.find();
});

Meteor.publish('post', function(id){
	return Posts.find({_id: id});
});

Hello,
you shoud return a cursor in a publication not an object

so replace findOne by find({_id: id}).
and you need to use {{title}} and {{body}} instead of {{post.title}} {{post.body}} in post template

i did that too but it doesn’t work. Do i need to create helper function as well after subscribing ??

hi i have updated the description can you please let me know if its the valid way to do because it works this way

Your code looks good. Maybe you can avoid calling the post helper twice, using by #with or another template:

<template name="post">
	{{#if Template.subscriptionsReady}}
  {{> loadedPost p=post}}
{{else}}
   Loading...
	{{/if}}
</template>

<template name="loadedPost">
	    <h1>{{p.title}}</h1>
	    <p>	{{p.body}}</p>
</template>

what i want to know is, in publish function i am publish using like this

Meteor.publish('post', function(id){
	return Posts.find({_id: id});
});

and in Template helper JS file i am again using this

Template.post.helpers({
	post: function(){
		return Posts.findOne(Router.current().params._id);
	}
});

I am guessing that by using template level subscription i am assigning data to template instance as well, so, why double calling find method to the collection when you are subscribing in template level like this

Template.post.onCreated(function(){
	var self = this;
	  self.autorun(function () {
	    self.subscribe('post', Router.current().params._id);
	});
});

I mean is this how usually template level subscription works?? Am i doing it right?

You are doing it all right.

However, you seem to be confused:

  • Publish/subscribe is the mechanism by which you decide which data is loaded on the client. It populates the client local cache with data from the server.
  • Your post helper is where you decide which data from the local cache will be displayed in your template.
    Because your app is simple, both queries are identical. But it is usually not the case.

Thank you so much :smile: