O'Reilly logo

JavaScript Web Applications by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Templates

If you’re used to interpolating server variables in HTML, templating will be familiar. There are a variety of templating libraries out there—your choice will probably depend on which DOM library you’re using. However, most of them share a similar syntax, which I’ll describe below.

The gist of JavaScript templates is that you can take an HTML fragment interpolated with template variables and combine it with a JavaScript object, replacing those template variables with values from the object. Overall, JavaScript templating works in much the same way as templating libraries in other languages, such as PHP’s Smarty, Ruby’s ERB, and Python’s string formatting.

We’re going to use the jQuery.tmpl library as the basis for the templating examples. If you aren’t using jQuery, or if you want to use a different templating library, the examples should still be useful; the templating syntax for most libraries is very similar, if not identical. If you want a good alternative, check out Mustache, which has implementations in a lot of languages, including JavaScript.

Created by Microsoft, jQuery.tmpl is a templating plug-in based on John Resig’s original work. It’s a well-maintained library and is fully documented on the jQuery site. The library has one main function, jQuery.tmpl(), to which you can pass a template and some data. It renders a template element that you can append to the document. If the data is an array, the template is rendered once for every data item in the array; otherwise, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required