250

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?

kdabir
  • 9,623
  • 3
  • 43
  • 45
Joel
  • 3,166
  • 5
  • 24
  • 29

8 Answers8

462

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.

Stephen Fuhry
  • 12,624
  • 6
  • 56
  • 55
Bobby
  • 18,217
  • 15
  • 74
  • 89
  • 2
    Works great, and just discovered that JS switch/case statements work nicely in template markup, too. – nickb Nov 09 '11 at 02:45
  • Awesome answer. Can you please also tell how can I use alternating classes when I am using templates? Like first
  • should get class a and next b?
  • – DivinesLight Nov 23 '11 at 07:18
  • 4
    @BlackDivine I know it's kind of late, but for alternating styles you should use ``:nth-child(even)`` and ``:nth-child(odd)`` CSS selectors, not change your template. – prayerslayer Aug 30 '13 at 08:41
  • its looking same as java scriptlets used for rendering variables in jsp – Dungeon Hunter Sep 05 '13 at 04:34
  • I ended up with this line at the end {{ } }}, because I had to change the <% %> wrapper and it still worked. – Nosebleed Feb 05 '15 at 12:24
  • You can even do conditional AND with double ampersand `&&` even if your editor flags it as bad – Ray Foss Oct 10 '17 at 14:54