How to use if statements in underscore.js templates?
I'm using the underscore.js templating function and have done a template like this:
<script type="text/template" id="gridItem">
<div class="griditem <%= gridType %> <%= gridSize %>">
<img src="<%= image %>" />
<div class="content">
<span class="subheading"><%= categoryName %></span>
开发者_运维技巧 <% if (date) { %><span class="date"><%= date %></span><% } %>
<h2><%= title %></h2>
</div>
</div>
</script>
As you can see I have an if statement in there because all of my models won't have the date parameter. However this way of doing it gives me an error date is not defined
. So, how can I do if statements within a template?
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>');
} %>
Here is a simple if/else check in underscore.js, if you need to include a null check.
<div class="editor-label">
<label>First Name : </label>
</div>
<div class="editor-field">
<% if(FirstName == null) { %>
<input type="text" id="txtFirstName" value="" />
<% } else { %>
<input type="text" id="txtFirstName" value="<%=FirstName%>" />
<% } %>
</div>
Responding to blackdivine above (about how to stripe one's results), you may have already found your answer (if so, shame on you for not sharing!), but the easiest way of doing so is by using the modulus operator. say, for example, you're working in a for loop:
<% for(i=0, l=myLongArray.length; i<l; ++i) { %>
...
<% } %>
Within that loop, simply check the value of your index (i, in my case):
<% if(i%2) { %>class="odd"<% } else { %>class="even" <% }%>
Doing this will check the remainder of my index divided by two (toggling between 1 and 0 for each index row).
You can try _.isUndefined
<% if (!_.isUndefined(date)) { %><span class="date"><%= date %></span><% } %>
From here:
"You can also refer to the properties of the data object via that object, instead of accessing them as variables." Meaning that for OP's case this will work (with a significantly smaller change than other possible solutions):
<% if (obj.date) { %><span class="date"><%= date %></span><% } %>
To check for null values you could use _.isNull
from official documentation
isNull_.isNull(object)
Returns true if the value of object is null.
_.isNull(null);
=> true
_.isNull(undefined);
=> false
精彩评论