Home > Article > Web Front-end > How to Call Meteor Methods from Template Helpers Using Reactive Variables?
Calling Meteor Methods from Template Helpers
In Meteor, template helpers provide a way to dynamically generate content for templates. One common requirement is to call server-side Meteor methods from within these helpers.
Meteor 0.9.3.1 introduced a new approach for this scenario:
Using Reactive Variables:
Create a Reactive Variable:
<code class="js">Template.helloWorld.created = function() { this.myAsyncValue = new ReactiveVar("Waiting for response from server..."); }</code>
Call the Method:
<code class="js">Meteor.call('getAsyncValue', function(err, asyncValue) { if (err) { console.log(err); } else { this.myAsyncValue.set(asyncValue); } });</code>
Use the Helper:
<code class="js">Template.helloWorld.helpers({ txt: function() { return this.myAsyncValue.get(); } });</code>
In this approach, the reactive variable this.myAsyncValue is attached to the template instance. The helper function returns the value of this variable, which is updated when the method callback fires.
Note: This approach requires the reactive-var package to be installed:
$ meteor add reactive-var
The above is the detailed content of How to Call Meteor Methods from Template Helpers Using Reactive Variables?. For more information, please follow other related articles on the PHP Chinese website!