Reputation: 43
So I have the following template, within which I would like to render a different template depending on the value of a session variable
<template name = "selectFrame">
<div class = "container">
<div class = "frameCarousel">
{{> Template.dynamic template=active data=this}}
</div>
</div>
</template>
My session variable, board, is set from a previous template and changes as I would like. I have the value of template set to active, a template helper which can be seen below.
Template.selectFrame.helpers({
active: function() {
return Session.get('board');
}
});
Template.body.events({
'click .btn-primary': function (event) {
event.preventDefault();
console.log(event.target.id);
Session.set('board', event.target.id);
}
});
The value of board is set to the name of the four different templates that I would like to be dynamic. Currently, only the Session default value is returned, with its corresponding template.
What needs to be added to allow each of the templates to be shown as my session variable changes?
Upvotes: 2
Views: 2691
Reputation: 26
Not seeing everything in your code, I'm not sure what you're doing wrong, but hopefully this example is simple enough to guide you. I tried to keep the HTML and JS as close to what you provided as I could.
<head>
<title>Meteor Dynamic Template</title>
</head>
<body>
<h1>Meteor Dynamic Template</h1>
{{> selectFrame}}
<br>
<button class="btn-primary" id="dynamic1">Set Template 1</button>
<button class="btn-primary" id="dynamic2">Set Template 2</button>
<button class="btn-primary" id="dynamic3">Set Template 3</button>
<button class="btn-primary" id="dynamic4">Set Template 4</button>
</body>
<template name="selectFrame">
<div class="container">
<div class="frameCarousel">
{{> Template.dynamic template=active data=this}}
</div>
</div>
</template>
<template name="dynamic1">
This is dynamic template 1.
</template>
<template name="dynamic2">
This is dynamic template 2.
</template>
<template name="dynamic3">
This is dynamic template 3.
</template>
<template name="dynamic4">
This is dynamic template 4.
</template>
and the js code:
if (Meteor.isClient) {
Template.body.created = function() {
Session.set("board", "dynamic1");
}
Template.selectFrame.helpers({
active: function() {
return Session.get('board');
}
});
Template.body.events({
'click .btn-primary': function (event) {
event.preventDefault();
console.log(event.target.id);
Session.set('board', event.target.id);
}
});
}
And here is a MeteorPad running this example: http://meteorpad.com/pad/CAtoogYaqHxPKecvA/
Upvotes: 0
Reputation: 5708
If there're just 4 templates, it's OK to use if-else statement as a typical solution. For the case of many templates, I'm not sure about the solution. Just wait for help from some pro :)
Upvotes: 0