【问题标题】:Backbone can't see a key passed to the template [duplicate]骨干网看不到传递给模板的密钥[重复]
【发布时间】:2015-10-03 11:32:39
【问题描述】:

为了使用主干/下划线模板,我有一个非常简单的代码。


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

问题是它看不到应该传递给模板的键“名称”。我还是不明白为什么。

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

【问题讨论】:

    标签: javascript backbone.js underscore.js templating


    【解决方案1】:

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

    编译步骤不是,您在其中传递要被模板替换的参数。相反,编译步骤产生一个函数。以您的视图模型参数作为第一个参数调用编译函数的结果将返回您的模板字符串,其中包含您的视图模型的替换值。

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

    另外一点:请注意,Backbone 视图已经为我们提供了方便的this.$el,因此我们不需要再次执行$(this.el) 步骤。

    【讨论】:

    • 抱歉,我好像在看一个有点过时的教程,并没有注意到规范页面上的变化:(
    【解决方案2】:

    更改

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



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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      相关资源
      最近更新 更多