使用带有外部JSON的Handlebars模板

时间:2012-07-13 00:14:25

标签: handlebars.js

我觉得自己真的很蠢,但我无法弄清楚这一点。我正在尝试使用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));

这很简单,我不理解,对吧?

2 个答案:

答案 0 :(得分:6)

在这里,您将一个Object传递给模板函数。

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));
  }

'推文'变量不是Object,它是一个数组。

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

 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.
  }

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

答案 1 :(得分:3)

您必须将字符串转换为对象,因为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.

}

相关问题