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:

<body>
{{> foo }}
{{> bar }}
{{> baz }}
</body>

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 Templates.bar.events.

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 comment