0

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> 
2
  • Then nested {%= SortOrderCount %} looks wrong to me Commented Apr 24, 2013 at 21:11
  • If you want logic in your templates you really might want to consider something a little more powerful than Underscore's template function (which is, by design, pretty minimal). I'd recommend looking at Moustache or Handlebars; both are very popular, and far more powerful than _.template. Commented Apr 24, 2013 at 22:57

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that nearly solved the problem. The only think that isn't working is the selected item. The HTML for the <option> tags is <option value="2" {%="(i" =="CurrSortOrder)" ?="" 'selected="selected" ''="" :="" ""="" %}="">2</option>
The selected item isn't working because it showing the actual tertiary condition in the source html. Read the bottom of my original post.
Yea, that should be the problem. Thanks guys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.