Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Taking your Meteor to the Spa

5.00/5 (1 vote)
8 Sep 2015CPOL1 min read 6K  
Replacing the main body's template using Template.dynamic in a Meteor Single-Page-App

Massaging your Main Body

So you want to swap out your main page's starting template with other templates? It's easy. First, to prepare your app for such, use Template.directive in your primary html file (perhaps named "main.html" and located in a "client" subfolder of your project) like so:

HTML
<body>
{{> mnuScheduler}} {{> Template.dynamic template=currentTemplate}}
</body>

So the template being used is currentTemplate. What's that? currentTemplate is actually a helper function on the body, which is in the .js file corresponding to the .html file above:

JavaScript
Template.body.helpers({
  currentTemplate: function () {
  return Session.get('curTemplate');
  }
});

So, whatever 'curTemplate' is currently set to, that is what the main page's template will be. So what is 'curTemplate' set to? At first, it's set to the Template that you want to be your "home page"'s template, like so (in the same .js file as shown above):

JavaScript
Meteor.startup(function () {
  Session.setDefault('curTemplate', 'dbilledPlatypus');
});

So the Template displayed on the main page starts out as, in this case, 'dbilledPlatypus'. Obviously, you have to have a Template with that name in your project, so it can be found and used.

HTML
<template name="dbilledPlatypus">
  . . .
</template>

Turning Up the Heat in the Sauna

So now what? You want to change the value of the 'curTemplate' session variable at times. For example, you might do it when a menu item is clicked. Take this menu item, for instance:

HTML
<template name="mnuPlatypi"><ul class="top-level-menu"><li> 
</li><li> <a href="#">Platypi</a><ul class="second-level-menu">
<li> </li><li id="mniOpenExisting" name="mniOpenExisting">Open Existing
</li><li>
                . . .</li></ul></li></ul></template>

To respond to the menu being clicked and change the value of the Template, add code like this to your .js file:

JavaScript
Template.mnuPlatypi.events({
  "click #mniOpenExisting": function (event) {
    Session.set('curTemplate', 'scheduleOpenExisting');
   }
   // TODO: Add the rest of the mni event handlers
}); // body events

So the 'curTemplate' Session var is changed to 'scheduleOpenExisting' and that Template then dynamically replaces the previous Template ('dbilledPlatypus') on the main page. You can, of course, change the current Template in similar fashion elsewhere in the code, in response to whatever. Due to using Template.dynamic, that's all there is to it! It's practically magic!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)