【问题标题】:Rails with Backbone.js and Handlebars带有 Backbone.js 和 Handlebars 的 Rails
【发布时间】:2012-07-23 05:59:00
【问题描述】:

关于我的应用程序:
- 我使用带有backbone.js(backbone-on-rails gem)和handlebars模板引擎的Rails 3.2.6。
- 创建了路线和视图,效果很好。我的看法:

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

-我创建了一个模板(在资产目录:assets/templates/peoples/index.hbs):

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

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

未捕获的 TypeError:无法调用 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);

【问题讨论】:

    标签: ruby-on-rails backbone.js handlebars.js backbone-views


    【解决方案1】:

    /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'];
    

    【讨论】:

      猜你喜欢
      • 2013-02-08
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      相关资源
      最近更新 更多