Search code examples
meteoriron-router

Meteor Iron Router load template based on dynamic name


I would like to load a meteor template using iron-router but the template that I'm loading needs to be dynamic, I have tried a couple different approaches but none are working.

My router

Router.route('/forms/add-form/:template', {
  name: 'addForm',
  layoutTemplate: 'layoutApp',
  waitOn: function() {
    return Meteor.subscribe('producersList');
  },
  data: function() {
    return Producers.find();
  }
}); 

The router go

Router.go('addForm', {template: this.template});

The url is fine now I first tried having this in my router

name: this.params.template,

But that doesn't work I'm now trying the following in my addForm template

{{> UI.dynamic template=formToLoad data=myDataContext}}

formToLoad:function(){
    console.log('aaaa ' + this.template);
}
});

Solution

  • You can pass data into template in route:

    Router.route('/forms/add-form/:template', {
      name: 'addForm',
      layoutTemplate: 'layoutApp',
      waitOn: function() {
        return Meteor.subscribe('producersList');
      },
      data: function() {
        return {
          producers: Producers.find(),
          formToLoad: this.params.template //here pass the template name
        }
      }
    });
    

    and in your template:

    <template name="addForm">
      {{> Template.dynamic template=formToLoad}}
    </template>
    

    Now if we run:

    Router.go('addForm', {template: 'someTemplateName'});
    

    It should load template with name 'someTemplateName'. Use camelCase syntax for template names because you will get syntax error with 'some-template-name' when you will define helpers or events for template.