Dynamically loading templates in Meteor.js

Here’s how to dynamically render templates, as of Meteor 0.9.4 – 1.0. All other answers were obsolete at the time of this writing.

Let’s say you’re editing a bunch of records, or creating a new one, and want to render either the update template, or the new template, based on some Session variables.

There are two ways to do this:

1) This is the officially recommended method for Meteor 0.9.4 or newer – it uses Template.dynamic:

<template name="records">
  {{> Template.dynamic template=whichOne}}
</template>

<template name="recordUpdate">
  ...
</template>

<template name="recordNew">
  ...
</template>

Template.records.helpers({
  whichOne: function () {
    return Session.get('edit') ? 'recordUpdate' : 'recordNew'
    // note that we return a string - per http://docs.meteor.com/#template_dynamic
  }
});

2) This works in various Meteor versions, but isn’t recommended officially because it’s unclear that the template is chosen dynamically:

<template name="records">
  {{> whichOne}}
</template>

{{! Note how "whichOne" is indistinguishable from a constant template name... }}
{{  ...like "recordUpdate" or "recordNew" below. }}

<template name="recordUpdate">
  ...
</template>

<template name="recordNew">
  ...
</template>

Template.records.helpers({
  whichOne: function () {
    return Session.get('edit') ? Template.recordUpdate : Template.recordNew
    // note that we return a Template object, not a string
  }
});

To pass a data context to the template, use:

{{> Template.dynamic template=whichOne data=myData}}

Leave a Comment