Using Handlebars templates with external JSON

安稳与你 提交于 2019-12-02 20:59:48

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.

You have to convert string into object, because Handlebar template wrap only object.

Try this

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.

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!