user3475602
user3475602

Reputation: 1217

Detect which template includes the current one in Meteor

I want to detect which template includes another, because I want to have a css class only for one specific template.

Here is how it should work:

<template name="includedTempl">    
      <div class="panel panel-default {{#if templateX}}specialCSS{{/if}}" id="{{_id}}">
</template>

Template.includedTempl.helpers({
    templateX: function() {
       if (this.includedBy('templX.html')) {
            return true;
       }
       return false;
    }
});

How can I do this? Any help would be greatly appreciated.

Upvotes: 0

Views: 71

Answers (2)

David Weldon
David Weldon

Reputation: 64312

In general it can be challenging for a child template to determine its parent context because it may be nested an arbitrary number of times. Therefore, it's often easier for the parent to provide a context to the child which triggers the desired behavior. Here's an example:

app.html

<body>
  {{> parentTemplate parentContext}}
</body>

<template name="parentTemplate">
  {{> childTemplate specialContext}}
  {{> childTemplate}}
</template>

<template name="childTemplate">
  <div class="{{isSpecialClass}}">
    <p>parent name: {{name}}</p>
  </div>
</template>

app.js

if (Meteor.isClient) {
  Template.body.helpers({
    // add some context to the parent do demo how it can be modified
    parentContext: {name: 'dave'}
  });

  Template.parentTemplate.helpers({
    specialContext: function () {
      // make a copy of the parent data context
      var data = _.clone(Template.instance().data || {});
      // modify the context to indicate the child is special
      data.isSpecial = true;
      return data;
    }
  });

  Template.childTemplate.helpers({
    isSpecialClass: function () {
      // grab the context for this child (note it can be undefined)
      var data = Template.instance().data;
      if (data && data.isSpecial)
        // add the 'awesome' class if this child is special
        return 'awesome';
    }
  });
}

Here, the parent template creates two child templates. The first child is given the parent context along with isSpecial. The template with isSpecial will contain a div with the awesome class. The only tricky part is that both the parent and the child helpers must use Template.instance to determine their context.

Recommended Reading

Upvotes: 1

M&#225;rio
M&#225;rio

Reputation: 1612

You need to access the Template Instance to get the parent name.

<template name="parent">
   {{> child }}
</template>

<template name="child">
   <p>
      My father is <b>{{ fatherTemplate abc=23 }}</b>
   </p>
</template>
Template.child.helpers({
  'fatherTemplate' : function(){
      return UI._templateInstance().view.parentView.name;
  }
});

Template.child.rendered = function(){
    console.log("Father Template name: ", this.view.parentView.name);
}

Upvotes: 1

Related Questions