1

关于我的应用程序:
- 我将 Rails 3.2.6 与主干.js(backbone-on-rails gem)和车把模板引擎一起使用。
- 创建了路线和视图,效果很好。我的观点:

  el: $('#lorem'),
  render: function(){
    var js = this.collection.toJSON();
    var template = Handlebars.compile($("#lorem2").html());
    $(this.el).html(template({articles: js}));
    console.log(js);
    return this;
  }

-我创建了一个模板(在资产目录中:资产/模板/人民/索引.hbs):

<script id="lorem2" type="text/x-handlebars-template">
    {{#each articles}}
       {{this.name}}
     {{/each}}
</script>

当我刷新页面时,我收到以下错误消息:

未捕获的类型错误:无法调用 null 的方法“匹配”

我认为模板文件可能是错误的:

<script src="/assets/templates/people/index.js?body=1" type="text/javascript"></script>

这包含:

    (function() {
            this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
            this.HandlebarsTemplates["people/index"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  helpers = helpers || Handlebars.helpers;
  var buffer = "", stack1, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;


  buffer += "<div class=\"entry\">\n  <h1>";
  foundHelper = helpers.title;
  stack1 = foundHelper || depth0.title;
  if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
  else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "title", { hash: {} }); }
  buffer += escapeExpression(stack1) + "</h1>\n  <div class=\"body\">\n    ";
  foundHelper = helpers.body;
  stack1 = foundHelper || depth0.body;
  if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
  else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "body", { hash: {} }); }
  if(stack1 || stack1 === 0) { buffer += stack1; }
  buffer += "\n  </div>\n</div>\n";
  return buffer;});
            return HandlebarsTemplates["people/index"];
          }).call(this);
4

1 回答 1

2

这种混乱/assets/templates/people/index.js表明您的 Handlebars 模板在您的 JavaScript 代码看到它们之前已被编译为 JavaScript。

如果你说$(x).html()哪里x不匹配,你会得到null回报。所以你的 DOM 中可能根本没有#lorem2,你只在HandlebarsTemplates["people/index"]. 这意味着您的这部分render

var template = Handlebars.compile($("#lorem2").html());

将失败并给您TypeError例外。尝试将其替换为:

var template = HandlebarsTemplates['people/index'];
于 2012-07-24T21:01:17.277 回答