Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use if statements in underscore.js templates?

People also ask

How do you use underscore in JavaScript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

Can JavaScript function include underscore?

Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private. You can check Underscore prefix for property and method names in JavaScript for some previous discussion.

What is _ each in JavaScript?

The _.each function accepts an array or an object, an iteratee function and an optional context object, the iteratee function is invoked once and in order for each array item The iteratee function provides 3 arguments item - The current iterated object (or value if an object was passed) i - The index of the iterated ...

Should I use underscore JavaScript?

the Underscore Prefix in JavaScript VariablesThe underscore _ is simply an acceptable character for variable/function names; it has no additional functionality. Underscore variable is the standard for private variables and methods. There is no true class privacy in 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.


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>