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="https://stackoverflow.com/questions/7230470/<%= 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?

8 Answers
8

Leave a Comment