user2858924
user2858924

Reputation: 433

Waiting data while dynamically loading templates in Meteor.js

In my meteor.js application, I am dynamically loading the templates;

  {{#DynamicTemplate template=getTemplate data=getData}}
    Default content when there is no template.
  {{/DynamicTemplate}}

When I am loading sub-templates, is it possible to wait to render the sub-template until sub-templates's data ready which comes from getData? I mean is there something like waitOn function of the iron-router that I can do? Thank you

Upvotes: 4

Views: 1266

Answers (2)

durrrr
durrrr

Reputation: 352

You can now use {{#if Template.subscriptionsReady}} in templates

or

Template.instance().subscriptionsReady() in js code. And of course you can use this keyword as the reference to the current template.

Upvotes: 0

user3374348
user3374348

Reputation: 4101

An approach you could take is to subscribe in the template's created function, then when rendering the template, first check each subscription's ready() and if they aren't all true, then render a loading display.

<template name="templateWithSubscription">
  {{#if ready}}
    <!-- actual content -->
  {{else}}
    loading...
  {{/if}}
</template>
Template.templateWithSubscription.created = function () {
  this.subscriptions = [
    Meteor.subscribe(/* ... */),
    Meteor.subscribe(/* ... */),
    /* ... */
  ];
};

Template.templateWithSubscription.destroyed = function () {
  _.each(this.subscriptions, function (sub) {
    sub.stop();
  });
};

Template.templateWithSubscription.helpers({
  ready: function () {
    return _.all(Template.instance().subscriptions, function (sub) {
      return sub.ready();
    });
  }
});

A similar approach can be used for other data sources (e.g. methods).

Upvotes: 3

Related Questions