How to iterate over an array of objects with jquery templates each command

Simon Lomax picture Simon Lomax · Apr 1, 2012 · Viewed 7.6k times · Source

In Javascript I have a User object that contains an array of department objects like so:

user = 
{
   departments: [
        {id: 1, name: 'Department 1'},
        {id: 2, name: 'Department 2'},
        {id: 3, name: 'Department 3'}
   ]
}

Using jquery templates (version 1.4.2) I want to render a <select> tag like so:

<select name="departmentId" id="department">
    {{each departments}}
        <option value="{{= id }}">{{= name }}</option>
    {{/each}}   
</select>

This doesn't produce any values in the option elements. How do access the id and name properties of each of the department objects with the template.

Answer

Danish picture Danish · Apr 27, 2012

Use it like

<select name="departmentId" id="department">
{{each departments}}
    <option value="${idField}">${textField}</option>
{{/each}}</select>