Thomas
Thomas

Reputation: 5089

Iterate through values with underscore.js

I have a template like this:

template: _.template('<% if (inputType == "select") {%><select id="<%= id %>" class="<%= contentClass %>" name="<%= name %>">....options should go here! </select><%}%></p>'),

In my model, one of the attributes is an array. Imagine the object I am working with looks something like this:

"contentType":"input",
"contentClass":"createProject_cat",
"placeholder":"Project Category",
"name":"createProject_cat",
"inputType":"select",
"id":"3",
"value":["1","2","3"]

In this example, I am looking to wrap 1, 2 and 3 from the value attribute in <option> tags and then output them between the two <select> tags from the template above.

I would like to wrap each of the values in the child array with an option tag and output in the above template. Is there a simple way to iterate through these values printing and outputting them from within the template?

Upvotes: 1

Views: 248

Answers (1)

Augustin Riedinger
Augustin Riedinger

Reputation: 22148

You can do the same as the if condition :

<% for(var i=0; i<value.length; i++) { %>
    <option value="<%= value[i] %>">
<% } %>

Upvotes: 4

Related Questions