Backbone 看不到传递给模板的密钥

Backbone can't see a key passed to the template

为了使用 backbone/underscore 模板,我有一个非常简单的代码。


HTML:

<script type="text/template" id="search_template">
    <div>Name comes here: <h4><%=name%></h4></div>
    <input type="text" id="search_input" />
    <input type="button" id="search_button" value="Search" />
</script>   
<div id="search_container"></div>

JS:


$(function(){
var SearchView = Backbone.View.extend({
    initialize: function(){
      this.render();
    },
    render: function(){
      var tmpl = $('#search_template').html(),
          compiled = _.template(tmpl, { name:'hello' });
      $(this.el).html(compiled);
    }
  });
  var search_view = new SearchView({ el: "#search_container" });  
});

问题是它看不到应该传递到模板中的密钥 "name"。我还是不明白为什么。

整个代码示例位于此处:http://plnkr.co/edit/7fV2azTh6cpjmUxIBHvJ?p=preview

您没有正确使用 Underscore's template method

编译步骤是而不是,您在其中传递要由模板替换的参数。相反,编译步骤 生成一个函数 。调用已编译函数的结果,将您的视图模型参数作为第一个参数,将 return 模板的字符串与视图模型的替换值。

render: function () {
    var tmpl = $('#search_template').html(),
    compiled = _.template(tmpl);
    this.$el.html(compiled({ name:'hello' }));
}

补充一点:请注意 Backbone 视图如何为我们提供方便 this.$el,因此我们不需要再次执行 $(this.el) 步骤。

改变

compiled = _.template(tmpl, { name:'hello' });



compiled = _.template(tmpl)({ name:'hello' });

_.template returns 接受要插入模板的数据的函数

http://plnkr.co/edit/GqFBvepfukIwDGLQa8Ki?p=preview