Accessing one sibling template from another in Meteor

I ran into a situation where I wanted to inject some text into a div in one template, from a sibling template’s event helper. So, the set-up is this:

We have a Session variable, "mySessionVar".

The main template is, "main.html". Within it are three inclusion helpers for templates: "foo.html", "bar.html", and "baz.html".

From template (event helper) "bar.html", we want to inject some text into a paragraph element with an id of "msg" located in the template "baz.html".

The relevant mark-up in the "main.html" template is:

{{> foo }}
{{> bar }}
{{> baz }}

Notice that all three inclusion helpers are located within the main template’s body tags. So, “main.html" is the parent of all three of these. Making use of  Meteor’s  API, and then following the objects down the rabbit hole, we get:

Template.instance().view.parentView._templateInstance.$('#msg').text( Session.get( 'mySessionVar') );

This line of code would in this case be within an event handler for

I’m the first to admit this seem’s a kludgy looking solution, and I haven’t had time to explore if there is a more elegant way.

Functionally, all this is doing is grabbing the parent view of the "bar.html" template ( main.html ) and accessing it’s template instance, so that we can access elements via jQuery selector.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s