Search code examples
jquery-templates

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


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.


Solution

  • Use it like

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