Nyxynyx
Nyxynyx

Reputation: 63619

Using IF statements in Underscore.js/Backbone.js templates

I am receiving a JSON object where one of the value is null. The JSON looks like:

[{"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)

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

Because I want to hide the entire div if no price is returned, I added the if statements:

<% 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

<% 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

Upvotes: 3

Views: 12535

Answers (3)

Moritz Roessler
Moritz Roessler

Reputation: 8611

Shouldn't it be a == (in this case !==) for comparison

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

e.g look at the warning of this Jsbin.com line

Upvotes: 1

Christoph
Christoph

Reputation: 51211

null is not undefined!

If your json-object is correctly decoded, then checking (price) or (price != null) should be fine.

Upvotes: 2

CaffGeek
CaffGeek

Reputation: 22054

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.

Upvotes: 4

Related Questions