Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 639
Nyxynyx Avatar asked Apr 19 '26 20:04

Nyxynyx


2 Answers

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.

like image 186
CaffGeek Avatar answered Apr 21 '26 10:04

CaffGeek


null is not undefined!

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

like image 26
Christoph Avatar answered Apr 21 '26 08:04

Christoph