我有一个非常简单的代码来使用主干/下划线模板。
<小时/>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
最佳答案
您没有使用Underscore's template method正确。
编译步骤不是您传入要被模板替换的参数的地方。相反,编译步骤生成一个函数。以 View 模型参数作为第一个参数调用编译函数的结果将返回模板的字符串,其中包含 View 模型的替换值。
render: function () {
var tmpl = $('#search_template').html(),
compiled = _.template(tmpl);
this.$el.html(compiled({ name:'hello' }));
}
另外一点:注意 Backbone View 已经为我们提供了一个方便的 this.$el
,因此我们不需要执行 $(this.el)
> 再次迈出一步。
关于javascript - 主干网看不到传递给模板的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32922049/