如何使用下划线模板呈现JS对象?

时间:2017-03-15 05:16:31

标签: javascript templates backbone.js underscore.js underscore.js-templating

我尝试使用下划线模板和Backbone.js渲染数据的JS对象。

我创建的数据如下图所示。

JS object data

然后,我看到了类似的问题 How to display a JS object with underscore templates?

我没有正确地知道Backbone.js集合和模型,但最近我理解了这些 我已经使数据插入了类似于源代码的集合。

//that's create view
wordCollection.add(wordList);
var view = new views.Livingword({collection:wordList});

//that's view 
render: function(templateName) {
        var template = _.template(templateName);
        this.$el.html(template({result : this.collection.category}));
        return this;
      }

然后,我写了html源代码。

  <% _.each(result, function(item,key,list){ %>
            <tr>
            <td><%- category[key].bedroom %></td>
            </tr>
          <% }) %>

但是,错误是打印Uncaught ReferenceError: category is not defined
所以当我运行时,我尝试调试控制台命令产生的collection console.log(this.collection.category);低于图片。 this.collection.category result

我认为创建数据是合适的,并且找不到错误的源代码 如何在html中呈现我的数据?

1 个答案:

答案 0 :(得分:2)

在每次迭代中,代码中的item将是“卧室”之类的值,它们是包含对象的数组。
因此,为了遍历并打印其中的每个项目,您需要另一次迭代。

<% _.each(result, function(arr, key, list){ %>
 <!-- Add <tbody>, <thead> etc with "key" here -->

  <% _.each(arr, function(item, key, list){ %>
     <tr>
        <td><%= item.audioSrc %></td>
     </tr>
  <% }) %>

<% }) %>

现在在上面的代码中,audioSrc是硬编码的。如果您知道要打印的所有属性,则可以执行此操作。如果你不是(它们是动态的),那么你需要另一次迭代来遍历项目的每个属性。

附注:

  • 不是在每个渲染上执行var template = _.template(templateName);,而是

    template: _.template(templateName), // one time
    render: function(templateName) { 
        this.$el.html(this.template({result: this.collection.category}));
        return this;
    }
    
  • 为传递给模板的内容提供有意义的名称。 result是一个模糊的名字。 category更好,但它是一个类别的地图,正确的命名是categories。所以this.template({categories: this.collection.category}。如果名称清楚,你可以更好地了解你在编写模板时所做的工作

  • 根据用法:this.collection.category,我很确定它应该是模型而不是集合。集合用于一组事物,你将使用它的模型数组,如this.collection.models 因此,对于所有更改,您的代码应该类似于

    template: _.template(templateName), // one time
    render: function(templateName) { 
        this.$el.html(this.template({categories: this.model.categories});
        // ---- This can be an Array or Collection instance -----^
        return this;
    }
    

    使用模板:

    <% _.each(categories, function(category, name){ %>
    <!-- Add <tbody>, <thead> etc with "name" here -->
    
      <% _.each(category, function(item, name){ %>
        <tr>
          <td><%= item.audioSrc %></td>
        </tr>
      <% }) %>
    
    <% }) %>