I see a lot of questions here and on stackoverflow related to ‘passing data between templates’. Nearly always the suggested solution is to use Session. I almost always avoid Session. I think it pollutes the global scope, it prevents you from running multiple instances of the template, and it leads to undisciplined separation of concerns.
I came across this interesting example which uses Session to preserve template state and rewrite it to work without the Session vars.
Attach a reactiveDict to the template instance onCreate. Use this to store state instead of global Session var!
Template.Restaurants.onCreated(function() {
this.state = new ReactiveDict;
this.state.set('currentRestaurant', null); // could set a default value here
});
this event handler will set the state of the reactiveDict on click
'click': function(e, t) {
t.state.set('currentRestaurant', this._id);
}
this helper is used to show/hide the menu template
currentRestaurant: function() {
// check whether this restaurant is selected. "this" refers to the current
// context, eg. the current restaurant in the loop
return Template.instance().state.equals("currentRestaurant", this._id);
},
menu template receives the selected id from data context instead of from Session
<template name="Restaurants">
<ul>
{{#each Restaurant}}
<li>
{{name}}
{{#if currentRestaurant}}
{{> menuItems restaurant=_id}}
{{/if}}
</li>
{{/each}}
</ul>
</template>
<template name="menuItems">
<ul>
<li class="menu">I'm a menu for {{restaurantName}}!</li>
</ul>
</template>
added this helper just to show we really got the id
Template.menuItems.helpers({
restaurantName: function() {
var restaurantMenu = Restaurants.find(this.restaurant).fetch();
return restaurantMenu[0].name;
},
})
Posted a fully working project to github.
App is hosted on meteor.com
http://scopedreactitivydemo.meteor.com/