2

I am new to Meteor and wondering how to solve what seems to me is a common problem.

Let's say I have a handlebars template listing restaurants:

<template name="Restaurants">
  {{#each Restaurant}}
    {{name}}
  {{/each}}
</template>

Now when user clicks on a restaurant template I want to display a menu for that restaurant.

I added a subtemplate named "menuItems" that contains all menu items for a given restaurant:

<template name="Restaurants">
  {{#each Restaurant}}
    {{name}} 
    {{> menuItems}}
  {{/each}}
</template>

I want to render only one instance of menuItems subtemplate when user clicks anywhere on Restaurant template (render only the menu items for the selected restaurant).

It should go something like:

Template.Restaurants.events({
'click' : function (e) {
       // This is where I need help - what's the right way to display only one subtemplate instance?
     }
});

My question is - how I can select and display only the correct menuItems template instance?

Also I would like to place menuItems template instance in DOM only after the click and not before (having all the menu items for all restaurants and only hiding those divs is not an option because of high number of those items in db).

If you think I should approach the solution in some other way please let me know, thanks!

2 Answers 2

4

You should use {{#if}} and Session. Like this:

<template name="Restaurants">
  {{#each Restaurant}}
    {{name}} 
    {{#if restaurantSelected}}
      {{> menuItems}}
    {{/if}}
  {{/each}}
</template>

By using Session, a reactive data source, you can set a global flag indicating whether a restaurant is selected.

Template.Restaurants.restaurantSelected = function() {
  // check whether this restaurant is selected. "this" refers to the current
  // context, eg. the current restaurant in the loop
  return Session.equals("restaurantSelected", this._id);
}

Whenever you change that session key, the value will update and the template will be redrawn. So, you can toggle it when clicking a restaurant:

Template.Restaurants.events({
  'click' : function (e) {
    // store the current restaurant ID
    // make sure the event selector is correct!
    Session.set("restaurantSelected", this._id);
  }
});

Edit For clarity's sake I created a complete example that you can copy into your project and try out.

2
  • Thanks for such an exhaustive answer Rahul!
    – vladimirp
    Dec 26, 2012 at 9:25
  • I almost always avoid Session. I think it pollutes the global scope. Also it prevents you from running multiple instances of the template. I recommend using a reactiveVar or reactiveDict scoped to the template instance.
    – ChatGPT
    Apr 16, 2015 at 7:04
1

I almost always avoid Session. I think it pollutes the global scope. Also it prevents you from running multiple instances of the template. I recommend using a reactiveVar or reactiveDict scoped to the template instance. Thanks to Rahul for starting a demo project. I took his example and modified it to show my recommended approach.

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 init 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.findOne(this.restaurant);
    return restaurantMenu.name;
  },
})

Posted a fully working project to github. https://github.com/white-rabbit-japan/scopedReactivityDemo

App is hosted on meteor.com http://scopedreactitivydemo.meteor.com/

Finally, answering a question in the comments

Meteor.call('updateDoc', docId, newData, (error, result) => {
if (error) {
  // Handle the error
} else {
// Set the editProductId value in editState using the result from 
the method
editState.set('editProductId', result);
}

});

2
  • Thanks for suggesting this approach! I've converted Session to ReactiveDict based on your example in my project. All seems to work fine until I found out that I can't seem to set ReactiveDict upon (successful) doc update in Meteor.methods(). Previously, I would call Session.set('editProductId', null); and it would work. Could you kindly let me know if it's possible to do so with ReactiveDict and how to do it, please? Thanks! Jun 21, 2015 at 6:58
  • sorry it's been a while, but would this work? Meteor.call('updateDoc', docId, newData, (error, result) => { if (error) { // Handle the error } else { // Set the editProductId value in editState using the result from the method editState.set('editProductId', result); } });
    – ChatGPT
    Apr 22, 2023 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.