在Underscore.js/Backbone.js 模板中使用IF语句

3

我收到了一个 JSON 对象,其中一个值是 null。JSON 如下所示:

[{"id":"1096","price":null,

现在,使用以下代码将NULL字符串输出到网页。 (我正在使用Backbone.js / Underscore.js中的模板引擎)

<div class="subtitle">$<%= price %></div>

因为我希望在没有返回价格时隐藏整个 div,所以我添加了 if 语句:

<% if (price) { %>
    <div class="subtitle">$<%= price %></div>
<% } %>

然而,它似乎仍然输出了 div.subtitle。我做错了什么?我也尝试了以下方法,但它们没有起作用。
<% if (typeof(price) != "undefined") { %>
    <div class="subtitle">$<%= price %></div>
<% } %>

<% if (price != null) { %>
    <div class="subtitle">$<%= price %></div>
<% } %>

<% if (price != "null") { %>
    <div class="subtitle">$<%= price %></div>
<% } %>

我怀疑这与在Underscore.js的模板中使用if语句有关


你确定你从数组中传递了一个单一的对象吗?我们能看到你整个的下划线模板以及你传递的值吗? - jackwanders
3个回答

4

嗯,你不想要吗(不带感叹号)

<% if (price) { %>
    <div class="subtitle">$<%= price %></div>
<% } %>

因为您当前的说法是,如果没有价格,则显示价格...这没有意义。


是的,你说得对!我改成了 if(price),但还是不行。我怀疑这与在 underscore.js 的模板中使用 if 语句有关。 - Nyxynyx

2

null 不等于 undefined

如果你的 JSON 对象被正确解码,那么检查 (price) 或者 (price != null) 应该是没问题的。


console.log(price) 给我返回一个 object。但是 if(!price) 不起作用! :-/ 我正在使用 backbone.js 的 this.myCollectionName.fetch() 来获取 JSON 对象并解码它。 - Nyxynyx
好的,那么这很明显。对象始终为真。console.log(price) 应该给你 null - Christoph

1

比较的时候应该用==(在这种情况下是!==

<% if (price !== null) { %>
    <div class="subtitle">$<%= price %></div>
<% } %>

例如,看一下这个Jsbin.com行的警告


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接