How to use Meteor methods inside of a template helper

There is now a new way to do this (Meteor 0.9.3.1) which doesn’t pollute the Session namespace

Template.helloWorld.helpers({
    txt: function () {
        return Template.instance().myAsyncValue.get();
    }
});

Template.helloWorld.created = function (){
    var self = this;
    self.myAsyncValue = new ReactiveVar("Waiting for response from server...");
    Meteor.call('getAsyncValue', function (err, asyncValue) {
        if (err)
            console.log(err);
        else 
            self.myAsyncValue.set(asyncValue);
    });
}

In the ‘created’ callback, you create a new instance of a ReactiveVariable (see docs) and attach it to the template instance.

You then call your method and when the callback fires, you attach the returned value to the reactive variable.

You can then set up your helper to return the value of the reactive variable (which is attached to the template instance now), and it will rerun when the method returns.

But note you’ll have to add the reactive-var package for it to work

$ meteor add reactive-var

Leave a Comment