Monday, May 10, 2010

Quick Tip: An Introduction to jQuery Templating

Discover the industry leader in Email Marketing.Try iContact for FREE today!

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");  

People who read this post also read :



If you liked my post then,

Subscribe to this site via Email:

Click here to Subscribe to FREE email updates from "itrickz", so that you do not miss out anything that can be valuable to you and your blog!!

DropJack!
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

0 comments: on "Quick Tip: An Introduction to jQuery Templating"

Post a Comment