Search code examples
meteoriron-router

Meteor - Multiple data contexts with Iron Router


I just started using Meteor and Iron Router.

Here I'm trying to use two data contexts but appearantly I'm doing it wrong. I've googled it but it doesn't seem this is a very common problem, but I guess it got to be possible to pass on two or more data contexts, right?

This is my routing.js

Router.route('/package/:_id', function () {
      //Returns the selected/clicked package
      var package = Packages.findOne({_id: this.params._id});
      //Returns all items in Items collection.
      var listItems = Items.find();
      this.render('PackageDetails', {data: package, listItems});
    });

My template in which I'm trying to use data from the both contexts (one to populate a dropdownlist and one to show data of selected package

<template name="PackageDetails">
    <label class="label label-default">Item type: </label><p>{{ item }}</p>
    <label class="label label-default">Quantity: </label><p>{{ quantity }}</p>
    <label class="label label-default">Id: </label><p>{{ _id }}</p>

    <form class="change-state">
        <div class="input-group">
        {{> sAlert}}
        <select class="form-control" name="state">
            <option selected="true" disabled>Select State</option>
            {{#each states}}
                <option>{{name}}</option>
            {{/each}}
        </select>
        </div><br>

        <div class="input-group">
        <input type="submit" value="Change state" class="btn btn-success"/>
        </div>
    </form><br>
</template>

I solved it by using helpers on the template which returned the data, but would prefer to get it all from the routing.

So any ideas about this? Is there a better approach to achieve this or is it possible to pass two data contexts via Iron Router, in that case, how?


Solution

  • Your data object declaring syntax is wrong, it should be :

    this.render('PackageDetails', {
      data: {
        package: package,
        listItems: listItems
      }
    });
    

    Then in your template, you can reference the data context using {{package.property}} and {{#each listItems}}.