Quick Tip: Working with the Official jQuery Templating Plugin


This Cyber Monday Envato Tuts+ courses will be reduced to just $3. Don't miss out.

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

Step 2 : Create your Template

  • 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.

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:

...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.

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.

  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

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?