In the third part of our series, let’s talk a little more about data contexts.

Even if you’re not subscribing in the router, you might still be setting a template’s data context at the route level.

So our next task is to get rid of all these data callbacks and instead use template helpers. This will make our code more explicit, and make things easier when it comes time to switch to React.

When Helpers Are Not Enough

When setting a data context such as {foo: "bar"} with Iron Router, you make the foo variable available both as a template variable accessible from your Spacebars templates with {{foo}}, and as a property on the template.data object accessible from template callbacks and events.

As a consequence, in some cases simply replacing Iron Router’s data callback by a template helper might not be enough, and you might also need to take a closer look at the rest of your template code, too.

If you want to avoid having multiple Router.current() calls throughout your code, a simple workaround is to set the variable once using Template.instance():

Template.finishSignup.onCreated(function () {
  Template.instance().token = Router.current().params.token;
});

// reuse Template.instance().token anywhere in your helpers, callbacks, or events

Note that this won’t be reactive, but it shouldn’t be a problem since route parameters don’t change on their own anyway. If you want to use a reactive version of this pattern, check out the Meteor Guide.

Everyting Old Is New Again

On a nostalgic note, while going through the codebase I found a lot of left-over, commented-out code from before Iron Router precisely for setting the data context through template helpers (except with session variables):

chapter: function() {
  return Chapters.findOne({slug: Session.get('currentChapterSlug')});
}

When Iron Router came out it seemed like a no-brainer to get rid of these helpers and stick data context management code in the router.

But as we ended up realizing, there’s such a thing as being too smart for your own good, and we’ve since come back to more explicit template-level data context declarations.