我觉得真的很蠢,但我想不通。我正在试用 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));
这很简单,我不明白,对吧?
最佳答案
这里您将一个对象传递给模板函数。
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.
}
发布您的模板也能提供更多帮助。
关于handlebars.js - 将 Handlebars 模板与外部 JSON 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11462494/