How to use if statements in underscore.js templates?
Solution 1:
This should do the trick:
<% if (typeof(date) !== "undefined") { %>
<span class="date"><%= date %></span>
<% } %>
Remember that in underscore.js templates if
and for
are just standard javascript syntax wrapped in <% %>
tags.
Solution 2:
If you prefer shorter if else statement, you can use this shorthand:
<%= typeof(id)!== 'undefined' ? id : '' %>
It means display the id if is valid and blank if it wasn't.
Solution 3:
Depending on the situation and or your style, you might also wanna use print inside your <%
%>
tags, as it allows for direct output. Like:
<% if (typeof(id) != "undefined") {
print(id);
}
else {
print('new Model');
} %>
And for the original snippet with some concatenation:
<% if (typeof(date) != "undefined") {
print('<span class="date">' + date + '</span>');
} %>