How to use if statements in underscore.js templates?

JavascriptTemplatesbackbone.jsunderscore.js

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

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

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>');
} %>

Solution 4 - Javascript

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>

Solution 5 - Javascript

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).

Solution 6 - Javascript

You can try _.isUndefined

<% if (!_.isUndefined(date)) { %><span class="date"><%= date %></span><% } %>

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoelView Question on Stackoverflow
Solution 1 - JavascriptBobbyView Answer on Stackoverflow
Solution 2 - JavascriptTonyTakeshiView Answer on Stackoverflow
Solution 3 - JavascriptSunnyRedView Answer on Stackoverflow
Solution 4 - JavascriptYasser ShaikhView Answer on Stackoverflow
Solution 5 - JavascriptSnowmonkeyView Answer on Stackoverflow
Solution 6 - JavascriptDamienView Answer on Stackoverflow
Solution 7 - JavascriptAnna TView Answer on Stackoverflow
Solution 8 - JavascriptCubiczxView Answer on Stackoverflow