简体   繁体   English

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

[英]Using IF statements in Underscore.js/Backbone.js templates

I am receiving a JSON object where one of the value is null . 我收到一个JSON对象,其中一个值为null The JSON looks like: JSON看起来像:

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

Right now, it is outputting a NULL string to the webpage with the following code. 现在,它使用以下代码向网页输出NULL字符串。 (I am using the template engine in Backbone.js/Underscore.js) (我在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: 因为如果没有返回price我想隐藏整个div ,我添加了if语句:

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

However it seems to still output the div.subtitle . 但是它似乎仍然输出div.subtitle What am I doing wrong? 我究竟做错了什么? I also tried the following but they did not work 我也试过以下但是没有用

<% 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 我怀疑这与在Underscore.js模板中使用if语句有关

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. 因为你现在说如果没有价格那么显示价格......这没有任何意义。

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)(price != null)应该没问题。

Shouldn't it be a == (in this case !== ) for comparison 不应该是== (在这种情况下!== )进行比较

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

eg look at the warning of this Jsbin.com line 例如,看看这个Jsbin.com线的警告

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

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