2015-10-03 40 views
0

爲了使用主幹/下劃線模板,我有一個非常簡單的代碼。主幹看不到傳遞給模板的密鑰


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

回答

2

您沒有使用正確Underscore's template method

編譯步驟是而不是您傳遞的參數將被模板替換。編譯步驟產生函數。以您的視圖模型參數作爲第一個參數調用編譯函數的結果將返回一個模板字符串,其中包含視圖模型的替換值。

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

另外一點:注意如何用骨幹查看已經爲我們提供了一個方便的this.$el,所以我們並不需要再次做$(this.el)一步。

+0

對不起,看來我在看一個小obsole te教程,並沒有注意到規格的頁面上的變化:( – srgg6701