Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Handlebars templates with external JSON

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:

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

That doesn't display anything in my template, but the following code works as expected:

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

This is something simple that I'm not understanding, right?

like image 763
Alex Lande Avatar asked Mar 11 '26 20:03

Alex Lande


1 Answers

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.

like image 188
Rajat Avatar answered Mar 13 '26 14:03

Rajat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!