Search code examples
javascriptbackbone.jsunderscore.jsunderscore.js-templating

How to add in else statement in underscore template


I have the following code:

var c = 'Credits: <% if (credits) { %> <%= credits %> <% } %> <% else  { %> N/A <% } %>'

However I get Unexpected token else. Is the else statement different than how the if statement is added? What should the above correctly be?


Solution

  • Just get rid of the %> <% between } and else. Like this:

    var c = 'Credits: <% if (credits) { %> <%= credits %> <% } else { %> N/A <% } %>';
    

    Alternatively, the ternary operator is one of my faves:

    var c = 'Credits: <%= credits ? credits : "N/A" %>';
    

    In case it's unclear, the ternary is basically a reduced if/else statement. The part before the ? is the expression being evaluated for truthiness. If it's truthy, the middle part between ? and : is executed, but if it's falsey, the last part after : is executed instead.