Quick Tip: Working with the Official jQuery Templating Plugin


Just this week, the jQuery team announced that Microsoft’s templating plugin (along with a couple others) is now being officially supported. What this means is that the plugin will now be maintained and updated directly by the core team. In this video tutorial, we’ll review the essentials of the plugin, and why it’s so awesome.


As a quick example, we’ll, again, refer to the Twitter search API example from Friday (think Bieber). The only difference is that, this time, we’ll use an HTML template to attach the returned data, rather than muddying up our JavaScript!

Months ago, Andrew Burgess introduced you to this plugin, still in beta. However, today, we’ll integrate the plugin into real-live code.


Crash Course


Step 1 : Import jQuery and the Templating Plugin

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="jquery.tmpl.js"></script>

Step 2 : Create your Template

<script id="tweets" type="text/x-jquery-tmpl">
	<li>
		<img src="${imgSource}" alt="${username}" />
		<h2> ${username} </h2>
		<p> ${tweet} </p>
		{{if geo}}
		<span> ${geo} </span>
		{{/if}}
	</li>
</script>
  • Notice how this template is wrapped within script tags, and that a type of text/x-jquery-tmpl has been applied.
  • We reference template variables names by prepending a dollar sign, and wrapping the property name within curly braces.
  • If statements can be created by using two sets of curly braces, as demonstrated above. (See screencast for more detail.)

Step 3 : Find Some Data to Render!

In this case, we’ll do a quick search of the Twitter search API.

<script>

 $.ajax({
    type : 'GET',
    dataType : 'jsonp',
    url : 'http://search.twitter.com/search.json?q=nettuts',

    success : function(tweets) {
       var twitter = $.map(tweets.results, function(obj, index) {
          return {
             username : obj.from_user,
             tweet : obj.text,
             imgSource : obj.profile_image_url,
             geo : obj.geo
          };
       });
    }
});

</script>

Thanks to Peter Galiba (see comments), for recommending the more elegant $.map solution, shown above.

Refer to the screencast for a full walk-through of the code above. Most importantly, though, is that we’re creating an array of objects. This will then serve as the data for the the template that we created in step two. Notice how the property names:

username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo

…correspond to the template variables that we created in step two.


Step 4 : Where Should the Mark-up Be Rendered?

Next, we must designate where the mark-up and data should be rendered. We’ll create an unordered list for this purpose.

    <ul id="tweets"> </ul>

Step 5 : Render the Data

Finally, we attach the data to the template, and append it to the unordered list (#tweets) that we created in step four.

$('#tweets').tmpl(twitter).appendTo('#twitter');
  1. Find the script (template) element with an id of tweets.
  2. Attach the twitter array to this template.
  3. Add the new mark-up to the DOM.

Final Source

<!DOCTYPE HTML>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title></title>
      <link rel="stylesheet" href="style.css" />

      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
      <script src="jquery.tmpl.js"></script>
   </head>
   <body>

      <h1> Tweets about Nettuts+ </h1>

      <script id="tweets" type="text/x-jquery-tmpl">
         <li>
            <img src="${imgSource}" alt="${userName}" />
            <h2> ${username} </h2>
            <p> ${tweet} </p>

            {{if geo}}
            <span>
               ${geo}
            </span>
            {{/if}}
         </li>
      </script>

      <ul id="twitter"></ul>

      <script>
         $.ajax({
            type : 'GET',
            dataType : 'jsonp',
            url : 'http://search.twitter.com/search.json?q=nettuts',

            success : function(tweets) {
               var twitter = $.map(tweets.results, function(obj, index) {
                  return {
                     username : obj.from_user,
                     tweet : obj.text,
                     imgSource : obj.profile_image_url,
                     geo : obj.geo
                  };
               });

               $('#tweets').tmpl(twitter).appendTo('#twitter');
            }
      });

      </script>
   </body>
</html>

So What do you Think?

Now that the templating plugin is officially supported by the core jQuery team, will you be using it in your future projects?