DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Use Template.dynamic to Create Dynamic Pages for Meteor Application


For a SPA (single page app), it's a common practice to switch between templates instead of pages. The following codes demonstrate how to switching between 2 templates according to 2 buttons' clicking events.

$ meteor create multipage
$ cd multipage
$ cat << EOF > multipage.html
<head>
  <title>multiple-view-example</title>
</head>

<body>
  <button class="pageHome">Home</button>
  <button class="pageAbout">About</button>
  {{> Template.dynamic template=whichOne}}
</body>

<template name="home">
  <p>Home!</p>
</template>

<template name="about">
  <p>About!</p>
</template>
EOF

$ cat << EOF > multipage.js
if ( Meteor.isClient ) {
  Meteor.startup(function () {
    Session.set("page", "home");
    console.log("session key: " + Session.get("page"));
  });

  Template.body.helpers({
    whichOne: function(){
      console.log("session key: " + Session.get("page"));
      return Session.get("page");
    }
  });

  Template.body.events({
    "click .pageHome": function () {
      Session.set("page", "home");
    },
    "click .pageAbout": function () {
      Session.set("page", "about");
    }
  });
}

if ( Meteor.isServer ) {
  Meteor.startup( function() {
  } );
}
EOF

$ meteor

Open http://localhost:3000, clicking "Home" button, the "home" template is shown. While clicking "about" button, the "about" template is shown.

Template.dynamic is better than Meteor's route package, for it's a built-in function of Meteor. No need to install a package with meteor add ....

And you can put big templates into a new html file, which make the struture more flexible.

Ref: http://stackoverflow.com/questions/12968808/dynamically-loading-templates-in-meteor-js



Published

Dec 3, 2014

Last Updated

Dec 3, 2014

Category

Tech

Tags

  • dynamic 2
  • meteor 47
  • template 4

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor