Search code examples
javascriptmeteormeteor-blazespacebarsmeteor-helper

How to use an array to render dynamically multiple templates in Meteor?


I am having problems with rendering templates using the data from the helper.

Template.bonus.helpers({
    Userform: function(){
      return UserForms.find({owner:Meteor.userId()});
    },
    warehouse: function(){
      return Warehouse.find({});
    },
    DisplayForm: [
      { formname: "SW - Picking" },
      { formname: "SW - Packing" },
      { formname: "SW - Putaway" }
    ]
  });

Basically I just want to achieve something like this:

<div id="placeholder" class="col-md-8">
    {{#each DisplayForm}}
        {{> {{formname}} }}       //Render 3 templates "SW - Picking","SW - ....
    {{/each}}
</div>

I am sure it is fairly easy but I just need the correct syntax so I can use data from helper as a name of a template to be rendered.


Solution

  • You can include a template dynamically in Meteor by using {{> Template.dynamic template=template [data=data] }}.

    For example:

    <body>
      {{> bonus}}
    </body>
    
    <template name="bonus">
      {{#each displayForm}}
        {{> Template.dynamic template=formname }}
        <br />
      {{/each}}
    </template>
    
    <template name="picking">
      Picking Template
    </template>
    
    <template name="packing">
      Packing Template
    </template>
    
    <template name="putaway">
      Putaway Template
    </template>
    

    if (Meteor.isClient) {
      Template.bonus.helpers({
        displayForm: [{
          formname: "picking"
        }, {
          formname: "packing"
        }, {
          formname: "putaway"
        }]
      });
    }
    

    Here is a MeteorPad.