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:
Solution 1:
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><templatename="parentTemplate">
{{> childTemplate specialContext}}
{{> childTemplate}}
</template><templatename="childTemplate"><divclass="{{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 contextvardata = _.clone(Template.instance().data || {});
// modify the context to indicate the child is specialdata.isSpecial = true;
returndata;
}
});
Template.childTemplate.helpers({
isSpecialClass: function () {
// grab the context for this child (note it can be undefined)vardata = Template.instance().data;
if (data && data.isSpecial)
// add the 'awesome' class if this child is specialreturn'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
Solution 2:
You need to access the Template Instance to get the parent name.
<templatename="parent">
{{> child }}
</template><templatename="child"><p>
My father is <b>{{ fatherTemplate abc=23 }}</b></p></template>
Template.child.helpers({
'fatherTemplate' : function(){
returnUI._templateInstance().view.parentView.name;
}
});
Template.child.rendered = function(){
console.log("Father Template name: ", this.view.parentView.name);
}
Post a Comment for "Detect Which Template Includes The Current One In Meteor"