Handlebars模板无法从Backbone处理JSON

egi*_*dra 3 javascript json backbone.js handlebars.js

Handlebars无法读取我将其作为上下文发送的JSON对象.

这是调用Mustache模板并为其提供上下文的函数:

render: function() {
  var source = $("#round").html();
  var template = Handlebars.compile(source);
  var context = JSON.stringify(this.model);
  console.log(context);
  var html = template(context);
  $(this.el).html(html);
  return this;
},
Run Code Online (Sandbox Code Playgroud)

这是我传递的JSON对象:

{"result":0,"friend1":{"firstName":"Ape","lastName":"Head","fbID":329018,"kScore":99,"profilePic":""},"friend2":{"firstName":"Ape","lastName":"Hands","fbID":32,"kScore":70,"profilePic":""}}
Run Code Online (Sandbox Code Playgroud)

这是Handlebars模板:

  <script id="round" type="text/x-handlebars-template">
    {{#with friend1}}
    <h2>{{firstName}} {{lastName}}</h2>
    {{/with}}
  </script>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Uncaught TypeError: Cannot read property 'firstName' of undefined
Run Code Online (Sandbox Code Playgroud)

Joe*_*Joe 10

替换此功能:

render: function() {
  var source = $("#round").html();
  var template = Handlebars.compile(source);
  var context = JSON.stringify(this.model);
  console.log(context);
  var html = template(context);
  $(this.el).html(html);
  return this;
},
Run Code Online (Sandbox Code Playgroud)

有:

render: function() {
  var source = $("#round").html();
  var template = Handlebars.compile(source);
  var context = JSON.parse(this.model.toJSON);
  console.log(context);
  var html = template(context);
  $(this.el).html(html);
  return this;
},
Run Code Online (Sandbox Code Playgroud)

template在这种情况下应该采用javascript对象.JSON.stringify返回JSON对象的字符串表示形式,而不是javascript对象.但你真正想要的是模型的属性.所以你可以通过toJSON或JSON.stringify(this.model)访问它们,但是你需要将它们转换回Javascript对象.