Search code examples
meteoriron-router

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


Solution

  • 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).