Reputation: 5013
I have parent template included with child template. I need to use parents ReactiveVar
from child template. I can use Session
method but for my requirement Session
method doesn't works. How do I access ReactiveVar value from parent templates?
HTML:
<template name="ParentTemplate">
{{> ChildTemplate}}
</template>
<template name="ChildTemplate">
//Some HTML content
</template>
JS
Template.ParentTemplate.onCreated(function () {
this.myvalue = new ReactiveVar(5); //I tried this.data.myvalue but doesnt works
});
Template.ChildTemplate.helpers({
'myhelper' : function(){
return Template.parentData(1).myvalue.get();
}
});
Upvotes: 2
Views: 2374
Reputation: 482
Another possible solution could be to pass the data to the child explicitly.
// js
if (Meteor.isClient) {
Template.parent.onCreated(function () {
this.reactiveV = new ReactiveVar(42);
});
Template.parent.helpers({
getReactiveVar: function() {
return Template.instance().reactiveV;
},
});
Template.parent.events({
'click button': function(e, tmp) {
tmp.reactiveV.set(tmp.reactiveV.get() + 2);
},
});
}
and in the template file:
<template name="parent">
<p>this is the parent!</p>
<button> var++ </button>
{{> child parentData=getReactiveVar}}
</template>
<template name="child">
<h3>
child template
</h3>
{{parentData.get}}
</template>
as you press the button you will see the child template update. If you needed to, you could also assign the parent data in some other way in the Template.child.onCreated
function.
This might provide loser coupling between the two templates.
Upvotes: 5
Reputation: 64312
Here's an example were the child is a direct descendant of the parent:
<template name="parent">
{{> child}}
</template>
<template name="child">
<p>{{parentValue}}</p>
</template>
In this case we can access the parent's instance variable like this:
Template.child.helpers({
parentValue: function() {
var parentView = Blaze.currentView.parentView.parentView;
var parentInstance = parentView.templateInstance();
// replace parentVariable with the name of the instance variable
return parentInstance.parentVariable.get();
}
});
If the two templates have a more complex relationship in the DOM, you can use something like this:
// replace .parent-class will the selector for your parent template
el = $('.parent-class')[0]
var parentInstance = Blaze.getView(el).templateInstance();
// replace parentVariable with the name of the instance variable
return templateInstance.parentVariable.get();
Upvotes: 5