Cry*_*tal 17 javascript underscore.js
我在模板中显示了libraryPrep对象的模态视图,如下所示:
if (_.isUndefined(this.libraryPreps)) {
this.$el.html(this.template({ }));
} else {
this.$el.html(this.template({ libraryPreps: this.libraryPreps.toJSON() }));
}
Run Code Online (Sandbox Code Playgroud)
当我有一个libraryPreps对象时,else语句有效.在我的模板中,我使用它像这样:
<select id="libraryPreps" >
<% if (!_.isUndefined(libraryPreps)) { %>
<% _.each(libraryPreps, function (libraryPrep) { %>
<option value="<%=libraryPrep.id%>"><%= libraryPrep.name %></option>
<% }); %>
<% } %>
</select>
Run Code Online (Sandbox Code Playgroud)
当我没有libraryPreps对象时,我没有得到我的模板来渲染,并且我在控制台上得到一个错误,即libraryPreps是未定义的.我在模板中检查未定义错误吗?我觉得我在骨干模态视图中以相同的方式检查它,但出于某种原因,在我的实际模板中,它似乎不起作用.我的模板符号是否正确?谢谢.
Ber*_*rgi 30
如果您将变量传递给函数,则会对其进行评估,并且会因为没有这样的变量而抛出错误.相反,在骨干视图中,您访问的对象属性始终有效(undefined如果不存在具有该名称的属性,则返回该值).
相反,你将不得不在其上使用typeof运算符,这甚至适用于未声明的变量(看看变量=== undefined vs. typeof variable ==="undefined"和JavaScript检查变量是否存在(定义/初始化) )):
<select id="libraryPreps"><%
if (typeof libraryPreps !== "undefined") {
_.each(libraryPreps, function (libraryPrep) { %>
<option value="<%=libraryPrep.id%>"><%= libraryPrep.name %></option><%
});
}
%></select>
Run Code Online (Sandbox Code Playgroud)
要_.isUndefined在模板中使用,您需要在模板中明确提供值.来自文档:
默认情况下,
template通过with语句将数据中的值放在本地作用域中.但是,您可以使用该variable设置指定单个变量名称.这可以显着提高模板能够呈现的速度.Run Code Online (Sandbox Code Playgroud)_.template("Using 'with': <%= data.answer %>", {answer: 'no'}, {variable: 'data'}); => "Using 'with': no"
因此,您可以编写如下模板:
<% if (!_.isUndefined(data.libraryPreps)) { %> …
<% if ("libraryPreps" in data) { %> …
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17189 次 |
| 最近记录: |