【问题标题】:Handlebar compiled html not recognizing template function in backbone.jsHandlebar编译的html无法识别backbone.js中的模板功能
【发布时间】:2012-11-20 15:49:21
【问题描述】:

我正在进行的项目目前正在使用 Backbone.js 创建一个网站,并使用 Handlebars (http://handlebarsjs.com/) 作为模板系统。我正在尝试创建一个子视图,将 json 文档中的值获取到相应的模板中,然后将其返回给父视图。

我遇到的问题是当我使用

Handlebars.Compile(referenceViewTemplate)

当我尝试使用替换令牌时,它无法识别 template 函数

this.template({ identifier: value })

模板代码为:

<div id="reference-template">
  <div class="id">{{id}}</div>
  <div class="reference">{{content}}</div>
</div>

主干模型是:

define(['underscore','backbone'], 
function(_, Backbone){
  var reference = Backbone.Model.extend({
     initialize: function(){}
  });
  return reference;
});

主干集合代码为:

define(['underscore','backbone','models/reference'], 
  function(_, Backbone, Reference){
  var References = Backbone.Collection.extend({
    model: Reference,
    parse:function(response){ return response; }
  });
  return new References;
});

父视图中调用引用视图的代码为:

this.ref = new ReferenceView();
this.ref.model = this.model.page_refs; //page_refs is the section in the json which has the relevant content 
this.ref.render(section); //section is the specific part of the json which should be rendered in the view

而ReferenceView中的代码是:

define([
  // These are path alias that we configured in our bootstrap
  'jquery','underscore','backbone','handlebars',
  'models/reference','collections/references','text!templates/reference.html'],
  function($, _, Backbone, Handlebars, Reference, References, referenceViewTemplate) {
    var ReferenceView = Backbone.View.extend({

    //Define the default template
    template: Handlebars.Compiler(referenceViewTemplate),   

    el: ".overlay-references",

    model: new Reference,

    events:{},

    initialize : function() {
      this.model.bind('change', this.render, this);
      return this;
    },

    // Render function
    render : function(section) {
       //this is where it says "TypeError: this.template is not a function" 
       $(this.el).append(this.template(References.get(section).get("content")));
       return this;
    }
});

我知道这需要阅读很多内容,我感谢任何抽出时间阅读的人,如果我还有什么可以澄清的,请告诉我。

【问题讨论】:

    标签: backbone.js underscore.js handlebars.js


    【解决方案1】:

    答案显然是我使用了错误的函数来编译 html。出于某种原因,我输入了Handlebars.Compiler 而不是Handlebars.compile

    这并没有解决我项目中的所有问题(现在正在传回模板,但没有输入值),但至少它向前迈出了一步。

    【讨论】:

    • 编译后的模板函数需要一个对象,{id: ..., content: ...} 在您的情况下,References.get(section).get("content") 可能不是那种格式,您通常需要在某处调用 toJSON()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2021-01-06
    • 2021-02-24
    • 2012-02-28
    相关资源
    最近更新 更多