【问题标题】:Using Handlebars templates with external JSON将 Handlebars 模板与外部 JSON 结合使用
【发布时间】:2013-09-06 22:05:15
【问题描述】:

我觉得自己很愚蠢,但我想不通。我正在尝试 Handlebars.js,但我无法让它显示来自 Twitter API 的数据。这是我得到的:

$.ajax({
  url : 'http://twitter.com/statuses/user_timeline/alexlande.json',
  dataType : 'jsonp',
  success : function( tweets ) {

    var source = $('#tweet-template').html();
    var template = Handlebars.compile(source);
    var context = tweets;

    $('#container').html(template(context));
  }
});

这不会在我的模板中显示任何内容,但以下代码按预期工作:

var source = $('#tweet-template').html();
var template = Handlebars.compile(source);
var context = { tweets : [
  { text : "This is a test tweet" },
  { text : "And this is yet another" },
  { text : "And you always need three test tweets, right?" }
]};

$('#container').html(template(context));

这很简单,我不明白,对吧?

【问题讨论】:

    标签: handlebars.js


    【解决方案1】:

    这里您将一个对象传递给模板函数。

    var context = { tweets : [
      { text : "This is a test tweet" },
      { text : "And this is yet another" },
      { text : "And you always need three test tweets, right?" }
    ]};
    
    $('#container').html(template(context));
    

    但在代码中不起作用:

     success : function( tweets ) {
    
        var source = $('#tweet-template').html();
        var template = Handlebars.compile(source);
        var context = tweets;
    
        $('#container').html(template(context));
      }
    

    那个'tweets'变量不是一个对象,它是一个数组。

    我认为那是你做错了。试试这个:

     success : function( tweets ) {
    
        var source = $('#tweet-template').html();
        var template = Handlebars.compile(source);
        var context = tweets;
    
        $('#container').html(template({tweets:context}));//wrap in an Object.
      }
    

    发布您的模板也可以提供更多帮助。

    【讨论】:

    • 是的,就是这样!非常感谢。
    • 哇,这在使用 MySQL 返回的数据时救了我的命。谢谢!
    【解决方案2】:

    您必须将字符串转换为对象,因为 Handlebar 模板仅包装对象。

    试试这个

    success : function( tweets ) {
    var source = $('#tweet-template').html();
    var template = Handlebars.compile(source);
    
    var context = $.parseJSON(tweets); // convert string into object.
    $('#container').html(template(context)); //wrap in an Object.
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 2017-07-04
      相关资源
      最近更新 更多