在我的主干模型中,我有一个像这样的对象
{
lunsize: "big",
type: {mike: "who", james: "him"}
}
在我的模板中,当我这样做时
<% _.each(type, function(sip) { %>
<%= sip %>
<% }); %>
我得到了预期的结果,即 who
和 him
。
想知道如何循环整个模型本身而不仅仅是类型字段。
PS:我正在使用toJSON()
将我的模型转换为js对象
最佳答案
您可以传递template
的variable
设置。这指示下划线创建一个需要给定名称的变量的函数,而不是使用 with
将范围更改为传递的数据对象的默认行为。
创建 Backbone 模板时,传递变量名称:
_.template(yourTemplate, null, {variable: "data"});
然后您可以通过模板内的变量名称访问数据:
<% _.each(data, function (val, key) { %>
...
<% }); %>
由于 with
相当慢,因此它具有渲染速度更快的额外优势。来自 the underscore docs :
By default, template places the values from your data in the local scope via the with statement. However, you can specify a single variable name with the variable setting. This can significantly improve the speed at which a template is able to render.
关于javascript - 模板中的 Backbone 模型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19618872/