javascript 在 Underscore.js/Backbone.js 模板中使用 IF 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11453458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using IF statements in Underscore.js/Backbone.js templates
提问by Nyxynyx
I am receiving a JSON object where one of the value is null
. The JSON looks like:
我收到一个 JSON 对象,其中一个值是null
. JSON 看起来像:
[{"id":"1096","price":null,
Right now, it is outputting a NULL
string to the webpage with the following code. (I am using the template engine in Backbone.js/Underscore.js)
现在,它正在NULL
使用以下代码将字符串输出到网页。(我在 Backbone.js/Underscore.js 中使用模板引擎)
<div class="subtitle">$<%= price %></div>
Because I want to hide the entire div
if no price
is returned, I added the if
statements:
因为我想隐藏整个div
if noprice
返回,我添加了if
语句:
<% if (price) { %>
<div class="subtitle">$<%= price %></div>
<% } %>
However it seems to still output the div.subtitle
. What am I doing wrong? I also tried the following but they did not work
但是它似乎仍然输出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>
<% } %>
I suspect this has to do with using if
statements inside Underscore.js's templates
我怀疑这与使用if
Underscore.js 模板中的语句有关
回答by CaffGeek
Uh, don't you want (no exclamation mark)
呃,你不想要(没有感叹号)
<% if (price) { %>
<div class="subtitle">$<%= price %></div>
<% } %>
Because you are current saying if there is no price then display the price...which makes no sense.
因为你现在说如果没有价格,那么显示价格......这是没有意义的。
回答by Christoph
null
is not undefined
!
null
不是undefined
!
If your json-object is correctly decoded, then checking (price)
or (price != null)
should be fine.
如果你的 json-object 被正确解码,那么检查(price)
or(price != null)
应该没问题。