我正在尝试使用下划线模板和 Backbone.js 渲染数据的 JS 对象。
我创建了如下图所示的数据。
然后,我看到了类似的问题。
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:未定义类别
所以我尝试调试运行时控制台命令产生的collection
console.log(this.collection.category);
如下图所示。
我认为创建数据是合适的,没有找到错误的源代码。
如何在 html 中呈现我的数据?
最佳答案
在每次迭代中,代码中的 item
将是“bedroom”等内容的值,这些值是包含对象的数组。
因此,为了遍历并打印其中的每个项目,您需要另一次迭代。
<% _.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> <% }) %> <% }) %>
关于javascript - 如何使用下划线模板渲染 JS 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42801598/