Using Handlebars templates with external JSON

前端 未结 2 541
走了就别回头了
走了就别回头了 2021-02-02 05:04

I feel really stupid, but I can\'t figure this out. I\'m trying out Handlebars.js, but I can\'t get it to display data from the Twitter API. Here\'s what I\'ve got:



        
2条回答
  •  天命终不由人
    2021-02-02 05:12

    Here you are passing an Object to the template function.

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

    But in the code that doesn't work:

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

    That 'tweets' variable is not an Object, its an Array.

    I think that is what you are doing wrong. Try this:

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

    Posting your template could help more as well.

提交回复
热议问题