Search code examples
meteormeteor-helper

Meteor: Using template variables in javascript upon template being rendered


I want to modify the DOM using javascript upon the template being loaded (rendered). However, I can't seem to get the variables which were passed to the template in the first place. It seems that the only place I can use those variables are in the HTML template itself or in the template helpers. But I want to execute javascript (that relies on those variables) when the template finishes rendering.

The html renders fine, but I gave it here for reference anyway.

HTML Template:

<template name="cityDataset">
    {{#each airports}}
    <li>{{name}}
        <ul>
            <li>{{description}}</li>
            <li><a href="{{mapLink}}" target="_blank">Directions from...</a></li>
        </ul>
    </li>
    {{/each}}
</template>

Javascript file:

Template.cityDataset.helpers({
  airports: function() {
    console.log("helper-name: " + this.name);        // New York City
    console.log("helper-country: " + this.country);  // United States

    return CityDatasets.findOne({name: this.name, country: this.country}).airports;
  },
});

Template.cityDataset.rendered = function() {
    console.log("name: " + this.name);        // undefined
    console.log("country: " + this.country);  // undefined

    // I want to do stuff here! But I can't get the name and country :(
    //
    // doSomethingCoolToDOM(this.name, this.country);

}

The result I get in the console is this:

> helper-name: New York City
> helper-country: United States
> name: undefined
> country: undefined

Solution

  • Inside of rendered, you need to use this.data to access the template's data context.

    Template.cityDataset.rendered = function() {
      console.log("name: " + this.data.name);
      console.log("country: " + this.data.country);
    }