Quick Tip: An Introduction to jQuery Templating
videos

Quick Tip: An Introduction to jQuery Templating

Tutorial Details
  • Technology: jQuery
  • Length: 5 Minute Video

JavaScript Templating is a neat idea: it allows you to easily convert JSON to HTML without having to parse it. At Microsoft’s MIX10 conference, they announced that they are starting to contribute to the jQuery team. One of their efforts is to provide a templating plugin. In this quick tip, I’ll show you how to use it!

You’ll need the data to template; you’ll likely retrieve JSON from your server; of course, Object / Array literals work just as well, so that’s what we use:

var data = [
		{ name : "John",  age : 25 },
		{ name : "Jane",  age : 49 },
		{ name : "Jim",   age : 31 },
		{ name : "Julie", age : 39 },
		{ name : "Joe",   age : 19 },
		{ name : "Jack",  age : 48 }
	];

The template is written in <script type="text/html"></script> tags; for each item in your JSON, the template will render the HTML; then, it will return the entire HTML fragment to you. We can get to the JavaScript values from within the template by using {% and %} as tags. We can also execute regular JavaScript within these tags. Here’s our template:

<li>
	<span>{%= $i + 1 %}</span>
	<p><strong>Name: </strong> {%= name %}</p>
	{% if ($context.options.showAge) {  %}
		<p><strong>Age: </strong> {%= age %}</p>
	{% } %}
</li>

To render the data with the template, call the plugin; pass the data to the plugin method; you can optionally pass in an options object as well. (These aren’t predefined options; they’re values you want to use within the template, perhaps for branching.)

$("#listTemplate").render(data, { showAge : true }).appendTo("ul");	

It’s that easy! Have fun with it! You can get the complete code for this quick tip on Github

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Eric

    Its sad that you switched to youtube for all your videos. i browse this site at work and i cant view youtube vids at work as they are blocked.

  • http://ds.laroouse.com piyanistll

    perfect tutorial thanks

  • http://www.avey.de Way

    You say it right guy, it has “a lot of potential”. I like it so thanks for this quick tip. It was clear and brief.

  • http://www.myunv.com/ Sunny Singh

    This is pretty cool and I’m sure it can be useful in many apps, but isn’t this not a good idea on regular websites? I mean data should be available even with JavaScript turned off, and shouldn’t rely on such technologies (except API requests). Let me know if I’m wrong.

    • http://wpcanyon.com Slobodan Kustrimovic

      Turned off javascript is same as IE6. Something website owners don’t want to support anymore, but only the big ones like facebook have the “cohones” to do that. :)

      • http://www.myunv.com/ Sunny Singh

        I agree I don’t really know many people who have JavaScript turned off while browsing the web, but why does data have to be served with it? JavaScript should be used for functionality, not for data, That’s reserved for server side and database manipulation or just pure html.

        Also what about things such as RSS feeds, no use of this technique there.

      • Strife

        “Turned off javascript is same as IE6″ its nothing like the IE6 situation, people who have Javascript turned off are generally disabled users, data served via Javascript will be inaccessible to their screen readers. IE6 will die a death one day, disabled users will always be around and will always rely on the responsibility of web devs/designers to make sites accessible to them.

      • Dom

        some company’s have javascript disabled for security reasons
        also some company’s still use internet explorer 6, for reasons unclear to me.

        These are generally big bureaucratic company’s where it is not as simple as to tell them to upgrade. So inevitably when designing for a customer, it may be painful to exclude people from such company’s to view your website during working hours.

      • http://markscott.co.nz Mark Scott

        The IE6 issue still remaining in companies is 99% of the time due to an old web app built for the company’s intranet that relies on the quirks of IE6 and that upgrading the code so they can upgrade the browser doesn’t show very much ROI, and boils down to if it ain’t broke don’t fix it.

        Do you really think employers want to upgrade users browsers so they can use the latest in technology and therefore have to rebuild their internal web app?

    • http://jaytillery.com Wordpress Wiz

      I agree with Sunny. What happens when javascript isn’t present? What about accessibility?

      • Dalibor Sojic

        This is not for “font page”… this is GREAT for backend…. or “internal” applications.

        I will use it in our web based project management system.

      • http://markscott.co.nz Mark Scott

        This would be mainly targeted at sites that require the user to have javascript to use the site, i.e. any site that relies on ajax for its target audience or drag ‘n drop functionality provided by JS libraries etc.

        And yes, some sites wont/dont need to support accessibility due to the task they serve, it all depends on your target audience, you build sites to target your users, not you or not your stakeholders but users, and if the user has to be able to see and hear and interact in a certain way then that’s how its GOT to be.

    • flyingfox

      Data WILL be available with JavaScript turned off in this scenario when your application design is smart.

      In order to receive JSON data the browser probably requested it via an AJAX call (so JS is turned on). If the AJAX call was triggered by a hijaxed link click, then with JS turned off, the link target will provide that same data you were about to render via JS (when your are a smart developer, as i mentioned).

      It’s the concept of graceful degradation – provide ajaxified data for the normal user and an old full-page-refresh version for the dinosaurs – or, if you have the balls, as Slobodan stated, just don’t care about the fossiles and let them know that they are bound for extinction (an alternative you should seriously consider when you don’t need the last 2% of customers for your site.)

    • http://tween.ir/ Hassan

      You’re missing a point. When you are Ajaxing your web-app or your website, you need to get the data from the server (either xml or json), format it and then change your DOM accordingly. The Templating plugin will make it easy to format that requested data. It’s not there to replace the accessible html.
      One other advantage of templating is the sepration of your js code and how the result will be formatted. It’s like the idea behind MVC.

    • http://www.yumji.com Benjamin

      “It’s not the weapon which kills people. It’s the human with the weapon.”

      people sayin’, javascript is a bad thing because, if you turn it off… there would be no functionality. but it’s not the javascript thing. it’s the question for a developer to use javascript as a tool and not to base an complete application on it.

      outdated browsers are a complete different thing… if you’re a good developer, you know how you deliver your information to every human on world. “cohones” doesn’t matter.

  • Nuno Santos

    Really nice plugin and very useful!

  • http://www.angelbotto.com AngelBotto

    Awesome thanks!!

  • http://twitter.com/michalkozak Michal Kozak

    Really grea tip, Andrew, thanks a lot. That’s the first time I actually hear of it. I’ll look into that for sure!

  • http://www.bigseadesign.com Adam

    I like the idea, I hope to see a better way of templating the if statements. I’d like to see what we have in PHP, so it’d be

    {% if ($context.options.showAge): %}
    Age: {%= age %}
    {% endif %}

    Or something to that effect. I think that’s much easier to look at instead of having 3 different curly braces.

    • Carlos

      Yes, but that is why Microsoft used the other curly bracket. They don’t make things too easy. I do like the PHP version you proposed better. You should suggest it to MS. They might listen. Or even let the jQuery guys know.

  • David Runion

    I agree that a javascript templating engine isn’t ideal when a back-end solution is possible (which will output the regular HTML to the user without requiring javascript), but obviously this has Ajax applications. I’d like to see more advanced tutorials that build on this topic.

  • http://www.sonergonul.com/ Soner Gönül

    Wow

    That’s very useful

    Thanks

  • http://www.engram.nu Niklas Larsson

    Really great plugin! Can’t wait to start using this.

  • http://twitter.com/xrommelx xRommelx

    really cool tip!!!

  • http://www.farotech.com/ dP

    Y is Microsoft working on cool shit like this and not pushing users to upgrade to the latest version of IE. To that is more important than a json parsing plugin.

    • http://www.enome.be Pickels

      How can you push the latest version of IE to a big organisation that relies on IE6 to make some of their applications work. These big organisation also include hospitals which use a lot of IE6. I don’t even know how Microsoft could force users to use a better version of IE. The only way to do this is for everybody to stop supporting IE6 right away. So if you are annoyed by IE it means you are still supporting it which means you are also part of the problem.

  • http://twitter.com/javizf nkm

    Nice tip. I think JS templating is the way to go when working with AJAX. No more spaguetti code :)

    I find this a very interesting topic and I’m currently doing some research on different approaches:

    - Mustache.js (http://github.com/janl/mustache.js), is a JavaScript implementation of the Mustache template system (http://mustache.github.com/) that aims for simplicity.

    Mustache.js is not designed to work directly with JSON (although it uses objects and arrays), but it has the advantage of being simpler and easier to use, IMO. Also, as there already exist implementations in other languages, you could share templates between your server side language (Ruby, PHP), client language (JS), or even directly from a database (CouchDB).

    - There is also JSON template (http://code.google.com/p/json-template/), which obviously works with JSON. It looks very powerful and already has implementations in Python, JavaScript and PHP. I haven’t tried this one yet.

  • http://michael.theirwinfamily.net Michael

    I must say… that’s pretty impressive. This definitely has use in AJAX applications. Thanks for the tip!

  • http://www.cbesslabs.com Bratu Sebastian

    I believe it’s a great idea. Imagine being able to take a template from a url ( an api description ) and your data to turn it into a service. Now that would be great. Or even have the javascript present the data to different devices.

    I agree that we can do this with css style sheets, but having the power to build everything from scratch is better than having to cope with the browser issues. Great tutorial.

  • http://www.twitter.com/mvrilo Murilo

    Really beautiful, thanks for the tip!

  • Stevan

    Nothing new here – check out jTemplates – have been using for a while and it is gr8

    http://jtemplates.tpython.com/

    This has been around for years

    • http://twitter.com/DavGarcia David Garcia

      Ive been using jTemplates for quite a while too with great success. Not sure why they are proposing a new template engine.

  • Wes

    Thanks for the demonstration. Im really happy I took a few minutes to watch it rather than an hour to figure it MS has repackaged PHP. Do we really need another version of PHP (and his kid brother ASP) with a new name and slightly different syntax? I dont think so. And I think MS needs to stop letting their boys walk out of the garage with old scripting languages repackaged. Push the ones we already have further along. Im a MS hater. They have a lot great products.

    • Wes

      Or should say, Im NOT a MS hater. They have a lot of…

    • http://www.enome.be Pickels

      If you compare a Jquery templating engine with PHP or Asp.net I think you should stay a little longer inside the garage working on your coding skills.

  • Khalil

    It’s very nice tutorial thanks

  • Pachito Marco Calabrese

    I’ve seen something similar and i think even better and powerful. It’s called Titan and it’s a opensource project developed from Drew Wilson. I’ve also asked to nettuts to write an article about Firerift and Titan … You can have more info here: http://code.drewwilson.com/entry/titan-an-introduction

  • bad bad bad

    These look a lot like JSP scriptlets…

    Deductive argument:
    1. JSP scriptlets should be avoided.
    2. This jQuery templating system is just like JSP scriptlets.
    3. This jQuery templating system should be avoided.

    Why scriptlets should be avoided:
    http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/web-tier/web-tier3.html#1097968

    • http://felixb.se Felix

      Thank you, I thought this looked familiar.

  • http://www.argyllstudios.com Tim

    Love it! This will come in handy for some upcoming projects I have!

  • http://www.tutarli.org Ali Görkem

    Good tutorial. this is some like server languages {% = , % , ?=. looks nice!

  • http://Todotweet.com Alex wolfe

    Would be great if you could provide the advantage of this over a normal js function. Thanks,

  • Nirali

    Gerat post! :)

    • http://www.facebook.com/profile.php?id=100000494066687 Kostas

      I’ve been hinakcg away on this with no success on my own dream host account.First, for me, I found that the jsproto.tbl file was in the src directory, not in the Linux_ALL_OPT.OBJ dir.Second, I’m assuming that the line “cp *.h /usr/include/js” is really meant to be “cp *.h $RUN/include/js” — otherwise you’d need root to copy those headers into the /usr directory.But besides that, I keep getting an error when I configure couchdb:configure: error: Could not find the jsapi header.Are Mozilla SpiderMonkey headers installed?Did you run into any similar problems?

  • http://www.jeffadams.co.uk Jeff Adams

    Interesting concept. I wonder how long before we see some sort of lightweight jQuery CMS popping up.

  • http://www.globalgrafiks.com saqib

    nice really coooooooool!!

  • http://webgeekph.com WebGeek Philippines

    Great Post, That’s very useful to me
    Cheers!

  • http://spotdex.com Davidmoreen

    I do not understand why I would use this?

    • Yep

      Same here. Seems rather pointless to do this in javascript.

  • MUhammad Jamil

    This is a very good improvement .

  • http://www.tenaxtechnologies.com java developer

    This is very similar to JSP scriplets.
    But I like the idea, I hope to see a better way of templating the if statements.
    Thanks.

  • http://www.jordanwalker.net Jordan Walker

    This has powerful implications combined with PHP for dynamic pages.

  • http://techravings.com Jaro

    I guess it’s going to conflict with Django template system. In Django templates also {% %} is used for template tags.

  • http://digitalfunction.com JeffryMckay

    This is great thanks for the post…

  • http://ahmedelbaz.com Ahmed Elbaz

    Good Tip…

  • http://www.notifywire.com Ian Drake

    Using the script tag is an interesting idea. I’ve been using a hidden div tag with all my templates in it.

    I have a very similar system where I use a hidden html segment, but I use a very simple binding mechanism. Instead of all the {%= MemberName%} I just use [MemberName]. I’m not sure the ability to do if statements is needed, as the data delivered from the server is usually pre-filterd.

    Either way, the results are much better than quoted HTML in javascript!

  • http://www.alexsandro.com.br Alexsandro

    Nice plugins, templates is always usefull.
    I’m happy cos Microsoft interests in jQuery Core.
    It’s will usefull for Visual Studio 2010.

  • http://crainbandy.com bryan

    Are you worried about javascript being disabled?

  • Ronny

    Wow, kudos to Microsoft! :)

  • http://jazzphotograph.com bali wedding photography

    woowww ,, great job for you. . .

  • http://www.visualwebeffects.com Hobbes

    IE6? are your F^*&^*&^ serious????? i stopped actively supporting IE long ago. and until MS actually releases IE9 then i won’t actively support it.

    But because of the way i code things by my nature, there are only a few irritating visual elements in my apps that are not compatible with IE. CSS3 constructs like rounded corners and such which is not a huge deal.

    If people are still using IE6 then they need to give there heads a shake, and wake up.

    the disabled is another issue. Accessibility in any app (web or pc) this feature is one of my top priorities.

    anyway, great tutorial. I like the idea of this, it has tons of great future potential. nice to see MS contribute something usefully to the community. I can see where i could use this in my current projects.

  • eponymous23

    When I try to run the demo code from github *as-is* I get an error:

    $(“#listTemplate”).render is not a function”, more…}

    Anyone else having this problem?

    • http://twitter.com/jeffreynolte Jeffrey Nolte

      Same here :(

      • Rich

        same here. looks like the project has been updated.

  • http://sarfraznawaz.wordpress.com/ Sarfraz Ahmed

    Now that is nice info and good move by Microsoft :)

  • http://www.soltani.dk Matt Soltani

    This is useful. Thanks for the short and simple tutorial!

  • http://www.gigamountz.com/terms_of_service Susan

    $author Awesome Blog Post! Can’t wait to read more content like this.