I have a template with some nested templates in Meteor:
<template name="collectingTmpl">
{{> firstTmpl}}
{{> secondTmpl}}
</template>
If I set a reactive var/dict in firstTmpl
with
Template.firstTmpl.events({
'click .class-name': function(event, template) {
template.state = new ReactiveDict;
template.state.set('someName', 'someValue');
}
});
I can get this value within the same template with
Template.firstTmpl.helpers({
myValue: function() {
Template.instance().state.get('someName');
}
});
but can I also retrieve the value being set in firstTmpl
from secondTmpl
?
I mean something like
Template.secondTmpl.helpers({
myValueFromAnotherTmpl: function() {
Template.firstTmpl.state.get('someName');
}
});
You could alternatively set the ReactiveDict
on the parent template which is collectingTmpl
.
// always initialize your template instance properties
// in an onCreated lifecycle event
Template.collectingTmpl.onCreated(function(){
this.firstTmplState = new ReactiveDict();
});
Then you can obtain references to this template instance property in child templates using this code :
Template.firstTmpl.onCreated(function(){
// warning, this line is depending on how many parent templates
// the current template has before reaching collectingTmpl
var collectingTmplInstance = this.view.parentView.templateInstance();
this.firstTmplState = collectingTmplInstance.firstTmplState;
});
Template.secondTmpl.onCreated(function(){
var collectingTmplInstance = this.view.parentView.templateInstance();
this.firstTmplState = collectingTmplInstance.firstTmplState;
});
Then you can use the standard Template.instance().firstTmplState
syntax in any of your 3 templates and they'll always point to the same ReactiveVar
instance defined as a property of collectingTmpl
.
If you take care on a currently issue of blaze (missing data context), you are able to access other templates vars by Template.parentData().
See this MeteorPad as a demo, the background color will be changed onn each player when pressing the button. the color is defined by their parent template:
http://meteorpad.com/pad/zoiAvwuT3XXE5ruCf/Leaderboard_Template_parentData_Bug
You may also read at GitHub PullRequest about some updates I suggest
https://github.com/meteor/meteor/pull/4797
Cheers Tom
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With