The desired end result, outputting items into the select list via jQuery:

There’s actually several similar ways this can be achieved as can be seen on this StackOverflow question. I’ve put a summary of this post as an answer on that question also.

To add scope to this post, here is a quote from Scott Gu’s blog post on the purpose of the templating system.

Client-side templates enable jQuery developers to easily generate and render HTML UI on the client. Templates support a simple syntax that enables either developers or designers to declaratively specify the HTML they want to generate. Developers can then programmatically invoke the templates on the client, and pass JavaScript objects to them to make the content rendered completely data driven. These JavaScript objects can optionally be based on data retrieved from a server.

At this point I’m going forward on the assumption you now have a rough understanding of the purpose of templating so I can focus primarily on getting this to work with a <select> list.

The first step is to setup the appropriate template structure. In this scenario, it’s the <option> block with the ‘value’ and ‘text’ properties needing substitution. The syntax for the substitution variables is wrapped by the two opening curly-braces and an equal sign, it’s name then followed by 2 closing curly-braces. A note here as this is JavaScript performing the substitutions, it is in fact case sensitive.

That last line with the .render() and .appendTo() is where the elegance lies, the set-up of reusable templates is extracted out of the actual call to map the data to the html elements. There are more features in the templating library, so check out this post for more examples.

The aim is to keep this post on the very narrow topic of just applying to a select list. So the actual implementation of the ajax-y request and response of JSON will come in a future post. The impact on the actual templating logic is trivial and limited to the what you pass to the .render() call.

Summary of the gothcas:

Escape your quotes (single and doubles).

The template must be in it’s own script block, not as a JavaScript var (string). Not sure why that is, I’m still investigating.

Ensure your selectors are working.

Ensure your output is wrapped in valid html elements, at the least a <div>.