Meteor: Render template inside a template

2019-06-10 04:38发布

问题:

I have a list of names on 'postlist' template. These are 'usernames' of the person who created the post. I have created a href link so that when a user clicks on the name, they are routed/directed to a new template 'viewpost' and able to view the full post document.

But, I would like the 'viewpost' template to get rendered where I have put {{> yield}} inside the 'postlist' template instead. How do I configure the layourTemplate because I already have one working for another part of the app.

Of course, this post document obviously should change according to which name the user clicks.

Think Meteor todos example. Depending on whether you click 'join' or 'signin', the relevant templates gets rendered.

So what I have is so far is as follows.

postlist.html (showing list of the 'fullname' field in post documents).

<template name="postlist"> 
<div class="container">
<div class="col-sm-3">
    {{#each post}}
    <li><a href="{{pathFor 'viewpost'}}" >{{fullname}}</a></li>
    {{/each}}
</div>
</div>
{{> yield}}
</template>

router.js

Router.map(function(){
this.route('postlist',{
  path: '/postlist',
  template: 'postlist',
  waitOn: function(){
    return Meteor.subscribe('posts');
  },
  data: function(){
    return {post: Posts.find({})};
}
});
this.route('viewpost',{
  path: '/viewpost/:_id',
  template: 'viewpost',
   waitOn: function(){
    return Meteor.subscribe('posts');
  },
  data: function() { return Posts.findOne(this.params._id); }
});
});

回答1:

Since there doesn't seem to be much of a content overlap between the 'viewpost' template and the 'postlist' template, I think it will actually be cleaner to just use {{> viewpost currentPost}} in place of the yield, and set the currentPost programmatically. For example, in the postlist template, you can have a currentPost variable that returns the data for the current post, like so:

Template.postlist.helpers({
    currentPost: function () {
        return Posts.findOne(Session.get('currentPost'));
    }
});

and just set the Session when you click on the link in the postlist template.