Rails с Backbone.js и Handlebars

О моем приложении:
— Я использую Rails 3.2.6 с backbone.js (жемтой backbone-on-rails) и механизмом шаблонов handlebars.
— Создал маршруты и представления, отлично работает. Мой взгляд:

  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>

Когда я обновляю страницу, я получаю это сообщение об ошибке:

Uncaught TypeError: невозможно вызвать метод 'match' для 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);

person user1344853    schedule 24.07.2012    source источник


Ответы (1)


Этот беспорядок в /assets/templates/people/index.js предполагает, что ваши шаблоны Handlebars компилируются в JavaScript до того, как ваш код JavaScript их увидит.

Если вы скажете $(x).html(), где x ничему не соответствует, вы получите null в ответ. Так что у вас, вероятно, вообще нет #lorem2 в вашей DOM, у вас просто есть скомпилированный шаблон в HandlebarsTemplates["people/index"]. Это означает, что эта часть вашего render:

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

потерпит неудачу и даст вам ваше исключение TypeError. Попробуйте заменить это на:

var template = HandlebarsTemplates['people/index'];
person mu is too short    schedule 24.07.2012