如何在Meteor中呈现带有预定义数据的静态页面

How to render a static page with predefined data in Meteor

本文关键字:数据 预定义 静态 Meteor      更新时间:2023-09-26

我想呈现一个简单的静态页面,其中的数据是从远程api获得的。例如,我想渲染一个页面与天气预报,我从一个外部服务。但是这行不通。

Template.myStaticPage.content = function(){
 Meteor.http('GET', 'http://someurl.com/api/weather', function(err, res){
   if(res){return res};
 })
}

那么,在一个页面上什么都不显示。如何将数据传递给模板,而不需要任何响应上下文,如mongo集合或会话?

通过Session中继数据:http://docs.meteor.com/#session

Template.myStaticPage.content = function(){
    return Session.get("weather");
}
//Will run when the template is created
Template.myStaticPage.created = function() {
    Meteor.http('GET', 'http://someurl.com/api/weather', function(err, res){
        if(res){Session.set("weather", res);};
    });
}

你需要小心javascript中的回调,当你使用回调时,返回语句不会传递给原始function,因为回调使它异步