I\'m rendering the same Handlebars template in multiple (arbitrarily many) locations on the same page. Inside each template, I want a button to toggle the visibility of a di
UPDATED ANSWER - METEOR 0.8.3
Meteor now provides the UI._templateInstance() function, which gives access to the template instance in template helpers. This allows for a much cleaner implementation:
1.
In the below HTML code, remove {{#with templateInstanceId=getTemplateInstanceId}}
2. Replace the JS code by this one:
var templateInstanceId = 0;
Template.divWithToggleButton.created= function()
{
this.templateInstanceId = ++templateInstanceId;
};
Template.divWithToggleButton.events(
{
'click button': function(event, template)
{
Session.set("visible", template.templateInstanceId);
},
});
Template.divWithToggleButton.visible= function()
{
return Session.equals("visible", UI._templateInstance().templateInstanceId);
};
FORMER ANSWER
I had the same requirement in my project: uniquely identifying a template instance for using with Session.set.
Here is my simple hack, using context replacement and a 'sliding' unique instance id (more on this later):
Anywhere in client code, put:
var templateInstanceId = 0;
UI.registerHelper('getTemplateInstanceId', function()
{
return templateInstanceId++;
});
Then use {{#with templateInstanceId=getTemplateInstanceId }} in templates you want to uniquely identify instances. With your example, it could be something like this (not tested):
HTML:
{{#with templateInstanceId=getTemplateInstanceId }}
{{#if visible}}
{{> UI.contentBlock}}
{{/if}}
{{/with}}
JS (client code):
Template.divWithToggleButton.events(
{
'click button': function(event, template)
{
Session.set("visible", this.templateInstanceId);
},
});
Template.divWithToggleButton.visible= function()
{
return Session.equals("visible", this.templateInstanceId);
};
Now about this strange 'sliding' unique instance id:
This id is updated at each template rendering, I found no other way. It means any new rendering will invalidate the unique id stored in the Session. New rendering occurs if your div contains reactive data sources. Depending on your case, this can be a problem or not.