Reputation: 110163
I need to modify someone else's code who's using backbone.js. Here is the code:
var titleMovieTmpl = _.template('
<h4 style="display: inline-block;">
<%= item.title %> (<%= item.year %>)
</h4>');
How do I add an if statement to this code, for example:
<%= item.title %> if (<%= item.year %>){(<%= item.year %>)}
So far, I now have:
var titleMovieTmpl = _.template('<h4 style="display: inline-block;"><%= item.title %>' <% if (item.year) { %> + '(<%= item.year %>)'<% } %> + '</h4><a href="javascript:void(0)" class="view-item">view title</a>');
But this gives me a syntax error on unexpected token %
. What is the issue in the above?
Upvotes: 0
Views: 783
Reputation: 14310
In my opinion it would be much more readable to keep that template separate, definitely as it becomes more complex. It will resolve your quoting / concatenating issues, and your IDE or editor should be able to handle it much better as well.
<script type='template' id='titleMovieTemplate'>
<h4 style="display: inline-block;">
<%= item.title %>
<% if (item.year) { %>
(<%= item.year %>)
<% } %>
</h4>
</script>
after that you can do the following in your script:
var titleMovieTmpl = _.template(document.getElementById('titleMovieTemplate').innerHTML);
Upvotes: 2