Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  23] [ 3]  / answers: 1 / hits: 164345  / 13 Years ago, mon, august 29, 2011, 12:00:00

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?


More From » templates

 Answers
30

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.


[#90368] Friday, August 26, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;