2012-07-13 59 views
2

我覺得真的很愚蠢,但我無法弄清楚這一點。我正在嘗試Handlebars.js,但我無法讓它顯示來自Twitter API的數據。下面是我得到了什麼:與外部JSON一起使用Handlebars模板

$.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)); 

這是一些簡單的,我不理解,對?

回答

6

在這裏,您將一個對象傳遞給模板函數。

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

'鳴叫'變量不是一個對象,它的數組。

我認爲這就是你做錯了什麼。試試這個:

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

發佈你的模板可能會有更多的幫助。

+0

是的,這是它!非常感謝。 – 2012-07-13 16:38:06

+0

哇,這在使用MySQL返回的數據的時候挽救了我的生命。謝謝! – 2014-03-02 23:55:29

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. 

}