handlebars.js - 将 Handlebars 模板与外部 JSON 结合使用

标签 handlebars.js

我觉得真的很蠢,但我想不通。我正在试用 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/

相关文章:

javascript - Metalsmith 布局导致 "no files to process"错误

javascript - Handlebars 和其他

handlebars.js - 如何使用Handlebars三元助手?

javascript - 用于循环对象数组并创建具有无限子列表的列表的 Handlebars

javascript - 如何在 Handlebars 模板属性中使用变量

javascript - 如何使用 Handlebars 模板动态加载不同的部分?

javascript - 如何检测{{#each pages}}中的页面是否为当前页面?

node.js - if 语句包含在 Handlebars 中

Meteor 模板 : Pass a parameter into each sub template, 并在子模板助手中检索它

node.js - 使用 Express Handlebars 注册组装 Handlebars 助手