Search code examples
node.jsmeteoriron-routerflow-router

Migrating to FlowRouter, need something similar to a template data context


So I've read a lot on the discussion of Iron Router vs FlowRouter.

I started my project using Iron Router, but since changed my mind and I'm currently migrating to FlowRouter.

Everything was going smoothly until I started migrating the comments section of my app. You see, this section is reused several times on the app, it serves as a comment section for news, posts, photos, videos, etc.

Example using IR's data context:

Router.route('/news/:slug', {
   name: 'newsItem',
   waitOn: function() { Meteor.subscribe('news.single', this.params.slug) },
   data: function() {
      return News.findOne({slug: this.params.slug});
   }
});

<template name="newsItem">
  <p>{{title}}</p>
  <p>{{body}}</p>
  {{> commentSection}}
</template>

The Comment collection schema has a "type" (to know to what type of "thing" this comment belongs to, news, photos, etc). That type was set on the "form .submit" event of commentSection template. Example:

'submit form': function(e, template) {
  e.preventDefault();
  var $body = $(e.target).find('[name=body]');
  console.log(template.data.type);
  var comment = {
    type: template.data.type,
    parentId: template.data._id,
    parentSlug: template.data.slug,
    body: $body.val()
  };
  Meteor.call('insertComment', comment, function(error, commentId) {
    if (error){
      alert(error.reason);
    } else {
      $body.val('');
    }
  });
}

This worked because the template data context contained the News item which in turn has a a type property as well.

How could I achieve something similar to this only using Flow Router without setting data on the template as it is recommended by the official guide?


Solution

  • You'll want to use a template subscription and a {{#with}} helper probably.

    Template.newsItem.onCreated( function() {
        Template.instance().subscribe('news.single', FlowRouter.current().params.slug);
    });
    
    Template.newsItem.helpers({
        item() {
            let item = News.findOne();
            if( item ) {
                return item;
            }
        }
    });
    
    <template name="newsItem">
        {{#with item}}
            <!-- Your existing stuff -->
        {{/with}}
    </template>