thatgibbyguy
thatgibbyguy

Reputation: 4123

Meteor Blaze error with Template Helper

Most of my template helpers result in blaze errors and I'm not sure why. What makes them more strange is that they do not block rendering or events from the templates at all, in fact, the app works fine.

The main issue is a messy, messy, console. An example of this is below:

Template.templatename.helpers({
    adminhelper: function(){
        var theUser = Meteor.user(),
            theUserId = theUser['_id'];

        if(theUserId == "XXX"){
            return true;
        }
    }
});

Just one way of checking which user is an admin user. This results in:

Exception in template helper: TypeError: Cannot read property '_id' of undefined
    at Object.Template.templatename.helpers.adminhelper (http://localhost:3000/client/lib/helpers.js?37db222f849959237e4f36abdd8eba8f4157bd32:5:23)
    at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2693:16
    at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1602:16
    at Object.Spacebars.call (http://localhost:3000/packages/spacebars.js?3c496d2950151d744a8574297b46d2763a123bdf:169:18)
    at Template.manage.Blaze.If.HTML.HEADER.HTML.DIV.class (http://localhost:3000/client/views/template.templatename.js?868248757c652b031f64adad0edec9e2a276b925:6:22)
    at null.<anonymous> (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2454:44)
    at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1795:16
    at Object.Blaze._withCurrentView (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2029:12)
    at viewAutorun (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1794:18)
    at Tracker.Computation._compute (http://localhost:3000/packages/tracker.js?192a05cc46b867dadbe8bf90dd961f6f8fd1574f:288:36)

Interestingly, client/views/template.templatename.js does not exist. I put all helpers in a helpers.js file, and all events in an events.js file.

For my route I have

Router.route('/theurl',function(){
    this.render('templatename');
},{
    waitOn: function(){
        return Meteor.user();
    }
});

What can I do to avoid these issues in the future?

Upvotes: 0

Views: 432

Answers (1)

David Weldon
David Weldon

Reputation: 64342

Just use a guard to check for the existence of Meteor.user() before extracting the _id. Waiting on Meteor.user() in the route doesn't work, as waitOn requires a subscription. Alternatively you can just do this:

Template.templatename.helpers({
  adminhelper: function() {
    return Meteor.userId() === 'XXX';
  }
});

An even better solution is to use the roles package.

Upvotes: 2

Related Questions