jQuery Templates: quick start and tips

[2011-01-29] dev, javascript, webdev, clientjs
(Ad, please don’t block)
In this post, I present a short example that should explain the basics of jQuery Templates and quickly get you started. It also demonstrates a technique to cleanly handle separators between array elements. This technique applies to many other templating engines, so read on even if you don’t plan on using jQuery Templates.

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:
  • Input: [ "css", "tips" ]
  • Output: [ { value: "css", last: false }, { value: "tips", last: true } ]}
Explanation: With this transformation, every array element indicates whether it is the last one or not. This allows us to conditionally insert a separator after every element except the last one.

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:

JavaScript first steps [ js, programming, intro ]
How many programmers does it take? [ geek, humor ]
CSS layout tips [ css, tips ]

More information: