为什么UnderscoreJS会抛出此错误?

时间:2016-04-20 16:27:51

标签: backbone.js underscore.js-templating

 刚刚使用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 以及如何解决?

 谢谢。

1 个答案:

答案 0 :(得分:3)

_.template()方法在最新版本(1.7.0之后)中发生了重大变化,

现在_.template的第二个参数是设置对象,而不是模板的数据。它返回一个模板函数,它接受数据并返回实际的HTML。

所以你应该做

 var my_template = _.template($('#search_template').html());
 var html = my_template(variables);