为什么 UnderscoreJS 会抛出这个错误?
Why is UnderscoreJS throwing this error?
只是玩 Backbone 和 Underscore,我 运行 遇到了这个错误:
ReferenceError: can't find variable: search_label
这是整个代码:
<!DOCTYPE html>
<head>
<title>Router Example</title>
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/template" id="search_template">
<label><%= search_label %></label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
<div id="search_container"></div>
<script type="text/javascript">
var SearchView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
var variables = {search_label: "My Search"};
var my_template = _.template($('#search_template').html(), variables);
this.$el.html(my_template);
}
});
var search_view = new SearchView({el: $('#search_container')});
</script>
</body>
</html>
为什么会报 search_label 怎么解决?
谢谢你。
_.template()
方法在最近的版本(1.7.0
之后)中有重大变化,
现在 _.template
的第二个参数是一个设置对象,而不是模板的数据。它 returns 接受数据的模板函数和 returns 实际 HTML.
所以你应该这样做
var my_template = _.template($('#search_template').html());
var html = my_template(variables);
只是玩 Backbone 和 Underscore,我 运行 遇到了这个错误:
ReferenceError: can't find variable: search_label
这是整个代码:
<!DOCTYPE html>
<head>
<title>Router Example</title>
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/template" id="search_template">
<label><%= search_label %></label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
<div id="search_container"></div>
<script type="text/javascript">
var SearchView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
var variables = {search_label: "My Search"};
var my_template = _.template($('#search_template').html(), variables);
this.$el.html(my_template);
}
});
var search_view = new SearchView({el: $('#search_container')});
</script>
</body>
</html>
为什么会报 search_label 怎么解决?
谢谢你。
_.template()
方法在最近的版本(1.7.0
之后)中有重大变化,
现在 _.template
的第二个参数是一个设置对象,而不是模板的数据。它 returns 接受数据的模板函数和 returns 实际 HTML.
所以你应该这样做
var my_template = _.template($('#search_template').html());
var html = my_template(variables);