Marty Wallace
Marty Wallace

Reputation: 35744

Meteor - query collection inside template

given the following simple template:

        <ul>
            {{#each customers}}
            <li>
                <a href="/{{this._id}}">{{this.customerName}}</a>
                <span class="department">{{this.departmentId}}</span>
            </li>
            {{/each}}
        </ul>

I want to replace departmentId with the department name. But that will require a query to the department collection like:

departments.find({_id: this.departmentId})

which doesnt seem to work inside a template.

How can this be done?

Upvotes: 1

Views: 133

Answers (1)

Geoffrey Booth
Geoffrey Booth

Reputation: 7366

Create a template helper:

Template.yourTemplateNameHere.helpers({
  getDepartmentNameFromId: function () {
    // 'departments' is a Meteor collection
    // 'this' inherits from the same 'this' in your template
    var department = departments.findOne(this.departmentId);
    if (department != null && department.name != null)
      return department.name;
    else
      return ""; // Or "Unknown Department" or whatever you want
  }
});

Then replace your fourth line thus:

<span class="department">{{getDepartmentNameFromId}}</span>

Why do you have to write all this code? Can't you do this within the template? Well, sorry, you can't. That's just how Handlebars is. It's very strict about separating code logic (helpers) from presentation logic (templates).

Note that you also need to make sure your departments collection is populated on the client, at least with the department names you'll need to find.

Upvotes: 1

Related Questions