(in parens)

Using Arrays in Templates

arrays, jquery, templates, tmpl

According to the official documentation, .tmpl()’s data parameter…

…can be any JavaScript type, including Array or Object.

The typical case would be to pass an object. This allows you to refer to the properties of that object by name in the template. Demo:

http://gist.github.com/1135981#file_using_arrays_as_templates.1.html

Another typical case would be to pass an object that contains an array of values (not objects). Demo:

http://gist.github.com/1135981#file_using_arrays_as_templates.2.html

The syntax for {{each}} gives the current value an accessible name: $value. That convention does not exist, however, outside of {{each}} and the documentation does not describe the syntax for accessing the current value of an array when the array is the root data item. After looking through the source for the plugin and playing with $item, I found that you can do it as follows. Demo:

http://gist.github.com/1135981#file_using_arrays_as_templates.3.html

$item.data contains the data that the current template is acting on. It refers to the same value throughout a template. It doesn’t, for example, refer to the current item in an {{each}} iteration. Keep in mind, though, that if .tmpl() is called with an array, the template is rendered once for each item in the array, which is why, in the above example, $item.data refers to each individual value, not to the array that was passed in.

Another example requiring the $item.data syntax is when .tmpl() is called with an object, but the object contains an array of values that will be passed to a nested template. Demo:

http://gist.github.com/1135981#file_using_arrays_as_templates.4.html