How to use if statements in underscore.js templates?
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.
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.
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>');} %>