Before you continue, you should probably read my overview of templating, as it introduces several concepts relevant to this post. The example presented here shows a list of articles on an HTML page. Each article has a title and tags.
Step 1: Load jQuery and jQuery Templates
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>Explanation: By hosting your code on a public server, you can get started quickly. For public websites, it usually makes sense to keep doing so.
Step 2: Apply the template (shown in step 3) to data
<script type="text/javascript"> // helper functions for template, separate from code var options = { markLast: function(elems) { ... }, // ... }; // data var articles = [ { title: "JavaScript first steps", tags: [ "js", "programming", "intro"] }, { title: "How many programmers does it take?", tags: [ "geek", "humor" ] }, { title: "CSS layout tips", tags: [ "css", "tips" ] } ]; // apply articleTemplate to articles $(document).ready(function() { articles.forEach(function(article) { $("#articleTemplate").tmpl(article, options) .appendTo("#content"); }); }); </script>markLast() performs the following translation:
Step 3: The template
<script id="articleTemplate" type="text/x-jquery-tmpl"> <b>${title}</b> [ {{each $item.markLast(tags)}} ${value}{{if !last}}, {{/if}} {{/each}} ] <br> </script>To define the template, we use the script trick mentioned in the template overview. The template shows the title in bold and then iterates over the tags (after transforming them via markLast()). The comma after the value is only shown if the current element is not last.
Step 4: The HTML body
<body> <div id="content"> </div> </body>All the body does is provide a slot, via the ID content, for inserting the template output.
The output, rendered:
More information: