Search code examples
meteormeteor-blazemeteor-accountsmeteor-helper

How to make global helper that returns users profile name?


How to make register helper that returns users profile name?

I want to make a global template helper that would show a users profile name in the view. So, the use case would be I have one template that list items, another for messages and another lastly displaying the item on its own page. This is what I have so far:

client/helpers.js

// if we used items as a example, make its so the item template can see the specific item.
Template.items.helpers({
  items: function() {
    return Items.find();
  },
});

Template.registerHelper("usernameFromId", function (userId) {
  var user = Meteor.users.findOne({_id: userId});
  return user.profile.name;
});

client/subscriptions.js

Meteor.subscribe('allUsernames');

server/publications.js

Meteor.publish("allUsernames", function () {
  return Meteor.users.find({}, 
    { fields: { 'profile.name': 1 }
  });
});

client/templates/item.html

<template name="item">
 {{usernameFromId user}}
</template>

This does nothing, where am I in error?

UPDATE

No changes yet, as I'm not sure what to do.


Solution

  • The code is actually correct. In order to make the global helper I had to change:

    var user = Meteor.users.findOne({_id: userId});
    

    to

    var user = Meteor.users.findOne({_id: this.userId});
    

    So the complete function is:

    Template.registerHelper("usernameFromId", function (userId) {
      var user = Meteor.users.findOne({_id: this.userId});
      return user.profile.name;
    });
    

    Thanks commentators!