Advertisement
JavaScript & AJAX

Quick Tip: Working with the Official jQuery Templating Plugin

by

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?

Related Posts
  • Web Design
    UX
    Walk Users Through Your Website With Bootstrap TourTour retina
    When you have a web application which requires some getting used to from your users, a walkthrough of the interface is in order. Creating a walkthrough directly on top of the interface makes things very clear, so that's what we're going to build, using Bootstrap Tour.Read More…
  • Code
    PHP
    Creating a Photo Tag Wall With Twilio Picture Messaging & PHPProcedural to oop php retina preview
    Twilio's recently announced Picture Messaging has vastly opened up what we can do with text messaging, now we can attach photos to our text messages and have them get used in different ways. In our case, we are going to build a Photo Tag Wall, which will contain photos linked to tags that will be displayed on a website.Read More…
  • Code
    JavaScript & AJAX
    Ember Components: A Deep DiveEmber components retina preview
    Ember.js is a JavaScript MVC framework that allows developers to create ambitious web applications. Although pure MVC allows a developer to separate concerns, it does not provide you with all the tools and your application will need other constructs. Today, I'm going to talk about one of those constructs. Ember components are essentially sandboxed re-usable chunks of UI. If you are not familiar with Ember, please check out Getting Started With Ember.js or the Let's Learn Ember Course. In this tutorial, we will cover the Web Components specification, learn how to write a component in Ember, talk about composition, explain the difference between an Ember view and an Ember component, and practice integrating plugins with Ember components.Read More…
  • Code
    JavaScript & AJAX
    Getting Into Ember.js: Part 5Getting into ember
    Editor's Note: The Ember.js team has shifted to an expedited release schedule and as of this publication date are on version 1.2.0. This tutorial was written pre-v1.0 but many of the concepts are still applicable. We do our best to commission timely content and these situations happen from time-to-time. We'll work to update this in the future. In part 3 of my Ember series, I showed you how you can interact with data using Ember's Ember.Object main base class to create objects that define the methods and properties that act as a wrapper for your data. Here's an example:Read More…
  • Code
    PhoneGap
    PhoneGap: Build a Feed Reader - Project StructurePhonegap feed reader@2x
    Although not specifically created to work together, jQuery Mobile and Cordova (also known as PhoneGap) are a very powerful duo to create hybrid, mobile apps. This series will teach you how to develop a feed reader using web technologies and these two frameworks. Over the course of this series, you'll also become familiar with the Cordova Connection and Storage Core Plugins and the Google Feed API.Read More…
  • Code
    JavaScript & AJAX
    Events and Real-Time Messaging in Chrome Extensions Using SimperiumImg 400
    Recently I had the opportunity to look into Chrome Extension development.  The scenario was pretty simple, I had to notify a group of users when someone from the group was using a website. A Chrome Extension was an obvious choice and after a bit of documentation I came across Simperium, a service that I could use to send and receive data real-time in my extension.Read More…