【问题标题】:How to pass json data to a meteor template如何将 json 数据传递给流星模板
【发布时间】:2014-08-22 05:38:04
【问题描述】:

我正在尝试将数据从 json rest api 传递到流星模板

我从这样的 HTTP GET 获取 JSON:

if (Meteor.is_client) {

    Meteor.http.call("GET", "https://public-api.wordpress.com/rest/v1/freshly-pressed", function (err, result){
        console.log(result.content);
    })
}

if (Meteor.is_server) {

}

我可以在浏览器控制台中看到 JSON 数据

如何将数据传递给模板?

【问题讨论】:

    标签: javascript json templates meteor http-get


    【解决方案1】:

    有多种方法,具体取决于您拨打电话的地点和使用的软件包。最简单的一种是使用 session 和 helper:

    HTTP.get(..., function(err, result) {
      Session.set('httpResult', result);
    });
    
    Template.myTemplate.json = function() {
      return Session.get('httpResult');
    };
    
    
    <template name="myTemplate">
      {{json.property}}
      {{#with json}}
        {{property}}
        {{otherProperty}}
        {{lotsOfProperties}}
      {{/with}}
    </template>
    

    【讨论】:

    • 感谢@HubertOG,它不起作用我可以从 URL 获取任何数据
    • 这样可以渲染一个json对象的属性,你可能在@Hugo的其他地方有错误。
    【解决方案2】:

    最简单的方法是将结果保存在变量中并在模板中使用#with。

     Meteor.http.call("GET", "https://public-api.wordpress.com/rest/v1/freshly-pressed", function (err, result){
        my_json = result.content;
    })
    

    模板:

    <template name="json_data">
       {{#with my_jason}}
          ...
       {{/with}}
    

    【讨论】:

    • 感谢@ErezHochman,但它不起作用,json 存储在变量中,但在浏览器中不显示任何内容
    • 将 "Session.get('init')" 添加到 "my_json" 帮助器和 "Session.set('init',True)" 到 http.call 回调。在进行 http.call 之前绘制模板,并且由于它不是反应模板,因此它不会自行刷新。使用模板调用 Session.get 会将该 Session 绑定为模板的依赖项(即使您对从 Session.get 获得的数据什么也不做,调用它就足够了。
    猜你喜欢
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    相关资源
    最近更新 更多