0

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?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
David542
  • 104,438
  • 178
  • 489
  • 842
  • this is duplicat of http://stackoverflow.com/questions/7230470/how-to-use-if-statements-in-underscore-js-templates – Dmitriy Mar 04 '16 at 23:56
  • what you are looking at is strictly speaking not backbone, but an underscore template: http://underscorejs.org/#template – Pevara Mar 04 '16 at 23:58
  • @DmitriyLoskutov using that answer I get `Uncaught SyntaxError: Unexpected token %`. This question also has to do with string concatenation in an if statement. – David542 Mar 05 '16 at 00:08

2 Answers2

2

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);
Pevara
  • 14,242
  • 1
  • 34
  • 47
  • thank you this is very helpful and I've been able to implement this successfully. For reference, could you also please show what the correctly concatenated string would be? I've been working on it for 15 minutes now and I can't get it to match up. – David542 Mar 05 '16 at 00:20
  • It's a template, no need to concatenate: `'

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

    view title'`
    – Pevara Mar 05 '16 at 00:22
1
<% if (item.year) { %> 
  (<%= item.year %>) 
<% } %>
Tholle
  • 108,070
  • 19
  • 198
  • 189