Search code examples
javascriptmeteoriron-routerpublish-subscribe

How to iterate through all existing users in a Meteor template?


I am trying to get all the users to be iterated on my home page template, but I'm having troubles getting it to work. I've been trying so many different techniques but this is what I've got now:

Server:

Meteor.publish('userList', function() {
  return Meteor.users.find({}, {fields: {username: 1, emails: 1, profile: 1}});
});

Routing:

Router.route('/', {
    name: 'home',
    template: 'home',
    waitOn: function() {
      return Meteor.subscribe('userList');
    },
    data: function() {
      return Meteor.users.find({});
    }
  });

HTML:

<template name="home">
    <h1>Home page</h1>
    {{#each userList}}
        <p>Test</p>
        {{userList.username}}
    {{/each}}
</template>

I think my problem actually lies in the {{#each}} block because I don't know what to call there. Not even the test text displays.


Solution

  • One way to solve your problem is to return {userList: Meteor.users.find()} in your data function:

    Router.route('/', {
        name: 'home',
        template: 'home',
        waitOn: function() {
            return Meteor.subscribe('userList');
        },
        data: function() {
            return {userList: Meteor.users.find()};
        }
    });
    

    Then, you could iterate through userList by changing your home template to:

    <template name="home">
        <h1>Home page</h1>
        {{#each userList}}
            <p>Test</p>
            {{username}}
        {{/each}}
    </template>