I'm working on a project in Meteorjs, but I have a problem in rendering some data.
The problem is: At the first template render, there is no html. Then I switch the template to a 'MAP' view and go back to my 'LIST' view, and now there is the html with the different trainers.
I have a routeController
that does some extras operations to get some data
from Algolia
, and push it into a data.trainers
array.
For example (in trainers_controller.js
):
data: function() {
var trainers_tab = [];
// algolia
var client = algoliasearch('XXXXXXXXX', 'XXXXXXXXXX');
var index = client.initIndex('myindex');
if(Meteor.user()) {
tab = Trainers.find({});
tab.forEach(function(trainer) {
index.getObject(trainer.doctor_id, function (err, content) {
if (err) {
console.error(err);
return;
}
// geoloc address
// TODO : retrieve training exact address
// push to array
trainers_tab.push({
objectID: content.objectID,
name: content.name,
city: content.city,
speciality: content.speciality,
photo: content.photo,
about: content.about,
email: content.email,
phone: content.phone
//address:
});
});
});
}
var data = {
params: this.params || {},
trainers: trainers_tab
};
return data;
}
I have exactly what I need in the data.trainers
.
Next I try to render the trainers into my template
with the base method of
{{#each trainer in trainers}}
Do some stuff in html yeah !
{{/each}}
I determine and can switch the view with the {{>TemplateDynamic }}
spacebar of Blaze.
Depending on where your function is defined, you can either use a ReactiveVar
and set it as data in your data
function, ie instead of returning data
, set the object to your ReactiveVar:
Template.foo.onCreated(function() {
this.myData = new ReactiveVar(null);
});
Template.foo.onRendered(function() {
// Run your data function here
const data = {
params: this.params || {},
trainers: trainers_tab
};
this.myData.set(data);
});
Finally, retrieve the data with a helper:
Template.foo.helpers({
data: function() {
return Template.instance().myData.get();
},
});
That way, if your template is rendered before the data is retrieved, it will be updated and re-rendered once myData is set in your function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.