Smith
Smith

Reputation: 3164

Using for loops and if statement in Underscore.js templates?

I need to put some UI logic in my underscore template but I am having a hard time getting the syntax down. I am using the template in an ASP.Net MVC .aspx view so I had to change the template settings to use {%= %}, {%- %}, and {% %}.

I am trying to generate a select list inside a table row using to model attributes, "SortOrderCount" and "CurrSortOrder".

This is what I have so far but it errors out and the i in my for loop gets outputted as a literal "i" character. The syntax is so awful...lol

  <td>{% if (CurrSortOrder) { %}
                <select> 
                   {% for (var i = 1; i <= {%= SortOrderCount %}; i++) { %}
                       <option value="{%= i %}" {%= i == CurrSortOrder ?      
                               selected="selected" : "" %}>{%= i %}</option>
                   {% } %} 
                </select>
      {% } %}
  </td>

EDIT - this what it looks now with Simon's code.

<option value="1" {%="(i" =="CurrSortOrder)" ?="" 'selected="selected" ''="" :="" ""="" %}="">1</option> 

Upvotes: 0

Views: 5306

Answers (1)

Simon Boudrias
Simon Boudrias

Reputation: 44609

Remember strings are still strings in templates between {% %}. You have some unescaped string there.

Also, you cannot nest templates tags. Some cleanup is needed:

<td>{% if (CurrSortOrder) { %}
            <select> 
               {% for (var i = 1; i <= SortOrderCount; i++) { %}
                   <option value="{%= i %}" {%= (i == CurrSortOrder) ?      
                           'selected="selected"'' : "" %}>{%= i %}</option>
               {% } %} 
            </select>
{% } %}</td>

Upvotes: 2

Related Questions