David542
David542

Reputation: 110163

String concatenation on if statement in underscore.js

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

Answers (2)

Pevara
Pevara

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

Tholle
Tholle

Reputation: 112787

<% if (item.year) { %> 
  (<%= item.year %>) 
<% } %>

Upvotes: 1

Related Questions