Quick Tip: Working with the Official jQuery Templating Plugin
Tutorial Details
- Topic: jQuery Templating Plugin
- Difficulty: Intermediate
- Format: Screencast
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
scripttags, and that atypeoftext/x-jquery-tmplhas been applied. - We reference template variables names by prepending a dollar sign, and wrapping the property name within curly braces.
-
Ifstatements 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');
- Find the
script(template) element with anidof tweets. - Attach the
twitterarray to this template. - 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?

Nice shot, but what about usability ? And SEO ? is it readable?
I can’t see anything there which would flag issues of usability and SEO.
As demonstrated, the templating plugin allows you a much faster way of rendering inputs, and the resulting content is HTML anyway.
The only thing that could cause these issues is how you use and implement it.
I seriously doubt that this will be read by search engines:
1. It’s inside a tag.
2. The MIME type of the code is “text/x-jquery-tmpl” which is not an official MIME type.
Also, even if the search engines do read the content, they will save stuff like ” ${username} “. To get the variable substitution you need JavaScript which the search engines don’t support.
In short: Don’t use a JavaScript templating engine if you want your code to be SEO friendly.
Okay, it seems the comment system didn’t escape the HTML tags I wrote in my comment (XSS, anyone?). Item #1 should read “It’s inside a script tag.”
@Hosting…, seeing as the content is being generated by JavaScript in the first place, negates any issue with using a template system. It would not matter if you used a templating system or not in this case, the result is the same.
If the content needs to be indexed, don’t put it in JavaScript to begin with, however, tweets do not need to be indexed so that is a non-issue in this case.
Shouldnt your website work without javascript aswell?
I think this is great, especially for admin interfaces but also websites, to make them superfast!
Usability: Depends solely on your HTML. Doesn’t matter if you use a JS templating engine or not.
SEO: It is not SEO friendly. Check my reply to Michael H.
Some really great stuff. Easy to implement, yet powerful. I really don’t like writing HTML in my JavaScript and this templating is really helping keep my code clean.
Thanks, Jeffrey
Ditto.
Very cool. Glad to see these being officially supported. Microsoft is on a roll this past month with the web community.
Cool in some way (clean separation bbetween HTML & JS) but you increase HTML size even for users who don’t have JS enabled. What about another JS or custom file extension like .tmpl or .tpl dedicated to templating?
Putting the template html in .tmpl or .tpl is a good idea and as you said will minimize the html code, but I prefer to see all my html code in one place from maintainability point of view.
And what about users who have JavaScript disabled?
One thing that I learned is that JavaScript was made for enhancing the user experience; from animations to ajax (otherwise it’s sent synchronously.) In here you’re utilizing JavaScript to dish out data, but that’s the job of a server side language or pure html.
You can always not let a user in if JS is not enabled. I think JS has gotten to the point now where it is an important part of building web apps. If someone wants to use your app, they should have to meet the requirements… which is not a hard thing to do. I mean how can someone watch a video on YouTube without flash? (I know…. HTML5, but not every browser supports that yet!)
I build a lot of web apps that company employee’s use internally. There are certain features these apps HAVE to have, so I will not let a user in without JS being enabled… At the same time I would never block a visit to a company’s corporate website because they had JS turned off. I am just saying there are places where you can force users to use JS and this template engine is perfect for those cases!
Force people to use JS? You have no idea how upset some people get because of this.
JavaScript has achieved tons of bad mojo over the years. Pop-up adds and bouncing alert boxes are just the beginning. Some of my friends rant about how annoying many web interfaces are; because truthfully, shiny blinking pink-and-orange menus aren’t appealing to the eye or the mind. Most of us also miss the times when you’d just been served a bunch of data on a plastic platter, and leave the interface where it’s usually in programs: Functionality.
I will also say this once again: JavaScript was not meant to serve data. While this example is tolerable, as you’ll at most find this sort of app on side-bars, but I see many people make the mistake of not making an alternative.
So yeah, your links won’t fade in nicely and fireworks will shoot in the background, but at least give the users a chance to see the links.
I’m not sure how you call it; gracefully degrading perhaps. But in here? It’s just flat-out. Use this and this or go away.
Try and disable JavaScript and go to sites like Google. There’s no fade-in effect or search suggestions, but it’s still a completely functional site. JavaScript only has to do with how you hand the data, not if to hand the data at all.
JavaScript has been unfairly pigeon-holed into being simply a way to add nice-to-have bling on websites or serving ads, but if you play around with the language and the libraries and experiment with it, you see that its application can be tremendously extended in ways that are still blowing my mind. Its an extremely powerful language, especially now with so much logic on the client side (not that that is a good idea from a security standpoint, but its reality). I have tried using this Microsoft template before, and it seemed clumsy, but maybe that was just the tutorials i was following. But using jquery + YQL or some 3rd party api to acquire / manipulate/mashup and model data before throwing it into database (if you even want to) is really fun.
and as far as server-side JavaScript – have you seen node.js?
It is not really a good thing to use .each for this, a more elegant way would be:
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});
It is less code, possibly better readable, and using the right function for the right task.
Hey Peter,
Good point. I always forget to use $.map. A for statement is of course being run either way, but I agree that this is more elegant.
Thanks! I’ll add a note to the article portion of the tutorial.
I can see the usecase for iterating or mapping the results when you refine them (ie filter upfront, adjust timezone values, sort, …),
but in terms of simple data push for display you can just as easily do
var twitter = tweets.results
then you use the same json names in your template as in the results, reducing chance of typos or confusion
Very nice tip! It would make the HTML code cleaner. Thanks!
I really don’t like the idea of having that much JavaScript in my html file. What if I’m working with a large page? It’s going to be more .js than .html.
Interesting concept though…
Julian – In the case where you’re building HTML fragments, you have it either way. You can still separate the JS out to its own external file.
Also, the JS in the HTML is valid, the script element is part of HTML. In JS though, HTML fragments are just strings
Jquery is like the EA of javascript APIs. Always behind, always stifling innovation through ridiculous copyright claims, and always stealing the best ideas then fruckin it up absolutely with a counterintuitive implementation. Jquery is an element selector that got bloated, now they have a million projects trying to saturate the web with pseudo innovation in hopes of one day coming up with a profitable business model.
Jquery is finished.
Yep – jQuery is dead.
Trolling Troll Trolls
Hey Jeff, awesome tutorial!
By the way, why the change in avatar. I like it in some ways more than the old one, mainly in how your name now shows up.
Nice job though!
Just time for a change. :)
Excellent article on jQuery Templating Plugin.
Thanks for sharing.
Been reading alot about this one lately, the more I read about it the more I like it. It is definitely a powerful tool when I is used in the right context.
templating shd be done on server side not client…what if the user accessing the site through mobile?
I think you’re misunderstanding the purpose of javascript templating: it’s not the whole pages :-)
But for example, if you have a progressively enhanced search form that can retrieve search results as you type in the search box (while non-javascript users would see results only when they send the form and load the next page), you want the server to return data as small as possible in order to make that realtime search results list as fast as possible, therefore the templating of these search results, even if it’s just a simple little list, is best done on the client side than on the server.
That’s why I think that it is useful for progressive enhancement, if used properly.
Awesome tutorial, thank you Jeff.
There is an error in step 4. Id should be “twitter” instead of “tweets” (it’s ok in final source). And it’s a nice tutorial, even if i prefer to use Pure templating engine. But it was good to see how alternatives work.
Another fantastic video Jeff! thanks
What about compatibility with Django templates? Django uses the same markup with double curly braces {{ }} to print out varialbes (like {{arg.id}}). There’s a potential conflict in there… anyone knows the solution???
OK, I’ve found discussion about this problem alreay in the Issues section on GitHub… Too bad that these plugin at this point doesn’t work nicely with Django…
http://github.com/nje/jquery-tmpl/issues#issue/17
Nice tutorial, spent the morning researching further. Also, at the end, “we’ll you be using it in your future projects?” it should it ‘will’ not ‘we’ll’
This is crap! The User can’t see any content when JS is disabled! I cant see progressive enhancement here. I hope this technique is never used by an professional web designer.
I think this code can be more useful for an app, not for a regular websites, Nice tutorial Jeffrey
What’s the vim plugin you use to do script[id=blabla, type=blabla]?
It’s called SnipMate.
Ok, for those (including myself) who don’t really like the idea of adding the templates via script tags, there are two to define a template (well three, but I dislike the method used by the “plus” extension of the tempalte plugin, so I’m sticking to the core version of the plugin)
http://snipplr.com/view/41590
The first method is the one described in the article, but the second one is even better because
you could retrieve the template from an external file (such as a .html) or even from a database
(which is what I will personally use it for).
And I think it would also fix the Django compatibility issue: I never used Django, but I would assume
that having the template stored outside the HTML page would fix the incompatibility.
(and here I wish I could edit my post to fix the breaklines and the few missing words :/ )
yep, thanks, it solves it to a large extent – a small hiccup is that since Django 1.2 all forms need to have this special CSRF (cross site request forgery) submit value generated by Django tag, so it would have to be added manually to a form generated from an external file
Javascript templates are fine, you’re just using them wrong. Javascript templates are made to reduce the amount of information that’s sent by the server on ajax calls.
For example, twitter: You’re searching for tweets, and there are 100+ new tweets each 5 seconds. Imagine how much html does the server need to send you each time there are new tweets – lets assume a tweet contains a lot of information and it’s markup is around 1kb.
100 tweets times 1 kb = 100 kb.
Now, imagine if you would only get a JSON markup of those 100 tweets for a total of 10 kb. Profit? It may not seem like a huge value, but imagine how much users does twitter have, any optimizations are more than welcome.
Not to mention this approach gives you more flexibility, because maybe some pages need the same content but display it differently – you could use the same data, and just serve it with different templates on their appropriate pages.
Of course, this approach has a downside – you have to write the templates twice. Once for your php code, and once for the javascript part, unless you use the same library for both php and js (well, I only know of Mustache that is available for both php and javascript).
Excellent tutorial, thanks very much for this!
I more of a noob at this but the “obj” var when you are filling the tweets variable, is that a reserved word in jQuery or is the placement of that word sprefic to the “each” function?
Great tutorial, and thanks in the future for the answers.
Ok… I’m not a big javascript person either but I will try to explain this how I understand it. I’m sure if I’m wrong many people will point that out.
The ‘obj’ is not a reserved word. It is, however, specific to the (callback?) function that is passed to the $.each method. The function (defined in $.each) is what you want to happen to each of the item/objects found in the first parameter of the $.each method (in this case the array tweets.results). That function has the index of the item/object as its first parameter and then a reference to the object itself (in this case obj) but Jeff could have just as well called it ‘kittyKat’. Then inside that function it would have been kittyKat.from_user… kittyKat.text… etc.
Hope I explained this correctly and effectively. Later!
Never knew it would be so easy! I added the created time and it came out with +0000 Greenwich time, is there a way to manipulate that to your own timezone? My settings are correct in twitter.
Once again Jquery provides a solution that people who aren’t by any means javascript experts can understand and use. That’s exactly what the project has always been about and continues to excel at.
Can’t understand the trolling, there may be lighter, tighter frameworks but there are none that do as much so well. Jealousy is an ugly emotion.
Whats the word of running something like this as server-side javascript?
I saw JQuery templates on some ASP.NET Blog and thought it is something from VS Developer, but it seem now all can use it.
It’s a very good tut, thanks for sharing..
Nice tutorial, thank you for sharing, I think I have some ideas where I can use it in my projects.
However, there’s a small error in the article. In Step 4 the code should be:
<ul id=”twitter”> </ul>
, as can be seen in the final source.
awesome stuff! I read up on this about 3 days ago on jQuery’s site and read the orig. author (of tmpl engine plugin) and was amazed, and the ideas flowed at great pace.
one way that this could be used is to remove semantic integration of ‘layout’s etc, and allows people to even further componentize views, subviews, etc… without ‘mucking’ around with html mixed with php code.
And it further removes back-end component output + html gener. + backend language interpretation (asp, php, etc…) into more of a front end management…
costs?
time to manip data, if the client is on a slower connection of sorts… or lots of things running. where as before this, one of the html+data is/would-be on the back-end.
but slick- no doubt!
Why should a website be indexed ? I really do not care
This is a fantastic tutorial. I first saw this in action at the Remix AU by James Senior.
Hey, thanks for the article
Tiny typo in Step 4, should read:
Instead of:
Hi
hope someone can help me.
all works great untill i want to display the template in a jquery ui dialog widget. then i get the html and curly braces and not the real content.
anyone know how can i display the template in a ui dialog?
best regards
hi, tmpl is amazing but boris moore (developer from ms who is extending this and building it out) is making this thing grow leaps and bounds – sometimes weekly… any chance this series can stay updated to include his views.js – data binding/etc?
https://github.com/BorisMoore
also, there is a framework called knockout – that is following closely with the growing trend – maybe just doing a knockout tut would get people warmed up to the framework so they could just use knockout – rather than chasing tmpl around?
just a thought :)
Thanks!