【问题标题】:Why is UnderscoreJS throwing this error? [duplicate]为什么 UnderscoreJS 会抛出这个错误? [复制]
【发布时间】:2016-04-20 16:27:51
【问题描述】:

只是玩 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 以及如何解决?

谢谢你。

【问题讨论】:

    标签: backbone.js underscore.js-templating


    【解决方案1】:

    _.template() 方法在最近的版本中发生了重大变化(1.7.0 更高版本),

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

    所以你应该这样做

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

    【讨论】:

    • 谢谢.....这个简单的知识解决了这个问题。
    • @Kneel-Before-ZOD 顺便说一下在视图定义中有template: _.template($('#search_template').html()) 并在渲染中执行this.$el.html(this.template(variables));... imo 更具可读性和一致性...
    • 好的.....记住这一点
    猜你喜欢
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多