Search code examples
javascriptmeteormeteor-blazemeteor-helper

Meteor ReactiveVar access parent tempate from child template


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();
 }
});

Solution

  • 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();