Search code examples
templatesmeteordynamicmeteor-blaze

Dynamically loading templates (partials) using Blaze Meteor.js


Is there any way to dynamically load a template with onCreated method of Meteor.js? I have different template and one display area (main template).

<template name="main">

</template>

default loaded template

<template name="default">
</template>

Loaded templates via links

<template name="page1">
</template>

<template name="page2">
</template>

Is there a way I can use oncreated function to load the default, and remove (default) and load other template in the same main template when they are clicked?


Solution

  • Check out Template.dynamic.

    It allows you to load a template only by its name. Easy thing here because you can let your template handle dynamic names by using a Reactive var or Reactive Dict.

    Declare some templates:

    <template name="main">
     {{> Template.dynamic template=getTemplateName }}
    
     <button class="loadTemplate" data-target="page1">Load Page 1</button> 
     <button class="loadTemplate" data-target="page2">Load Page 2</button> 
    </template>
    
    <template name="page1">
    </template>
    <template name="page2">
    </template>
    
    <template name="default">
    </template>
    

    In your main template you can set in onCreated the default template name default:

    Template.main.onCreated(function(){
      this.state = new ReactiveDict();
      this.state.set("targetTemplate", "default");
    })
    

    Get the template to load via helper:

    Template.main.helpers({
      getTemplateName() {
        return Template.instance().state.get("targetTemplate");
      },
    })
    

    And set the new template name by button click event:

    Template.main.events({
      'click .loadTemplate'(event, templateInstance) {
        event.preventDefault();
        const targetName = $(event.currentTarget).attr('data-target');
        templateInstance.state.set("targetTemplate", targetName);
      }
    })
    

    You can of course do this also by other events than only by clicking a button, since it depends on a ReactiveDict / ReactiveVar it will render the new template if the variable updates.

    Note: Very important is to handle the data that is passed to the template, too. Once your dynamic template becomes more complex you have to be more aware of that, too.