简体   繁体   English

模板中的骨干模型对象

[英]backbone model object in template

In my backbone model, I have an object like this 在我的骨干模型中,我有一个像这样的对象

 {
   lunsize: "big",
   type: {mike: "who", james: "him"}
}

In my template when I do this 在我的模板中,当我这样做

<% _.each(type, function(sip) { %>
<%= sip %>

<% }); %>

I get expected result which is who and him . 我得到的预期结果是whohim

Wondering how I would loop over the entire model itself and not just the type field. 想知道如何循环整个模型本身,而不仅仅是类型字段。

PS: I am using toJSON() to convert my model into an js object PS:我使用toJSON()将我的模型转换为js对象

You can pass the variable setting of template . 您可以传递templatevariable设置。 This instructs underscore to create a function expecting a variable of the given name, rather than its default behavior of using with to change scope to the passed data object. 这指示下划线创建一个期望给定名称的变量的函数,而不是使用with来将范围更改为传递的数据对象的默认行为。

When creating your Backbone template, pass a variable name: 创建Backbone模板时,传递变量名称:

_.template(yourTemplate, null, {variable: "data"});

You can then access your data by that variable name inside the template: 然后,您可以通过模板中的变量名访问数据:

<% _.each(data, function (val, key) { %>
  ...
<% }); %>

As with is quite slow, this has the added advantage of faster rendering. 由于with相当慢,这有更快的渲染的额外优势。 From the underscore docs : 下划线文档

By default, template places the values from your data in the local scope via the with statement. 默认情况下,template通过with语句将数据中的值放在本地作用域中。 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. 这可以显着提高模板能够呈现的速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM