jquery.jsontemplate.js Documentation

Download

Getting Started

You may need this extension if you...


place a template on the page inside a display none or otherwise hidden container. this is an html snippet that we will use to generate the rows of data;

API methods

$.fn.JSONTemplate(templateSelector[any valid jquery selector],json [array or object])

This is the core templating method. It accepts a javascript object or array and replaces all html elements inner html that have classes named after field names in the json array.

An HTML element like this would be replaced by the value of object.fieldname if the incomming json data looked like this {fieldname:'i am a value'}. <div class='field-fieldname'></div> The templater would generate this html <div class='field-fieldname'>i am a value</div>

$.fn.getJSONTemplate(
templateSelector[any valid jquery selector],
jsonUrl [a string with the URL of the script which outputs data in a json format],
params[and object which gets translated as key value pairs and appended to the query string of the URL see $.fn.getJSON],
complete[function - called with one argument. the json data returned from the ajax request. this is called after the ajax and render has been completed],
beforeComplete [optional function - called before any templating the value returned from this function will be used to build templates]
);

if you need to get your json data from the server directly you may do so via ajax.

$.fn.getJSONPTemplate

this method is a wrapper for the getJSON method. it helps set the callback correctly.

$.fn.outerHTML

This method is a general use helper method. You can return the outerHTML which is the innerHTML and the element's html as a string.
This also acts as a wrapper for replace if you pass a selectable value as the argument.


Demo with basic json data. ($.fn.JSONTemplate)

$(function(){ var json = [{food:'taco',type:'cold'},{food:'chicken',type:'grilled'},{food:'beef',type:'roast'}]; $("#results").JSONTemplate(".food-template",json); });

Demo with json data retrieved via ajax. ($.fn.getJSONTemplate)

$(function(){ $("#results").getJSONTemplate(".mood-template",'server.php',{action:'generate-rows'},function(data){ //data should be all rendered by now! },function(data){ //this is fired before i start rendering and if defined i must return data or a copy of data //this allows you to "flatten" or otherwise alter the json data before it goes to the template return data; }); });
Shuffled moods:

Demo with twitters api, ajax, and JSONP. ($.fn.getJSONPTemplate)

$(function(){ $("#tweets").getJSONPTemplate(".tweet-template",'http://twitter.com/statuses/user_timeline.json',{ screen_name:'soldair', count:5 },false,function(json){ //you can edit the response json here and must return a new value var out = json; $.each(out,function(k,v){ // i could parse the incomming data to make the date more attractive var created = out[k]['created_at']; var parts = created.split(' '); created = parts[0]+' '+parts[1]+' '+parts[2]; out[k]['created_at'] = created; }); return out; }); });

SOURCE:

/* * jQuery json template plug-in v0.0.4 * * Copyright (c) 2009 Ryan Day * http://ryanday.org * 18 - aug - 2009 * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($){ $.fn.extend({ getJSONPTemplate:function(templateSelector,jsonurl,params,complete,beforeComplete){ this.getJSONTemplate(templateSelector,jsonurl+"?callback=?",params,complete,beforeComplete); return this; }, getJSONTemplate:function(templateSelector,jsonurl,params,complete,beforeComplete){ var contentArea = this[0]; if(contentArea){ $.getJSON(jsonurl,params,function(json){ if(typeof beforeComplete == 'function'){ this.cb = beforeComplete; json = this.cb(json); } //do templating here $(contentArea).JSONTemplate(templateSelector,json); //stop templating if(complete){ this.cb = complete; this.cb(json); } }); } return this; }, JSONTemplate:function(templateSelector,json){ var templateTagOpen = '%'; var templateTagClose = '%'; var contentArea = this[0]; var template = $(templateSelector).clone()[0]; if(template){ /** *this allows you to handle a one row type result * takes a basic object as an argument * {taco:'happy',price:1.50} * and turns it into * [{taco:'happy',price:1.50}] * we can itterate over it without changing the multi dimensional array type data structure logic in the loop. * * the != 'object' check allows you to work with true multi dimensional arrays *[as opposed to the assumtion of an array of objects (aka: associative arrays or hashes)] * * [['one','two','three'],['one','two','three']] */ if(!json[0] || typeof json[0] != 'object') json = [json]; var regExps = {}; $.each(json[0],function(k,v){ fields = $(template).find(".field-"+k); if(fields.length){ var tag = templateTagOpen+k+templateTagClose; fields.html(tag); regExps[tag] = new RegExp(tag); } }); var compiled = ''; var templateString = $(template).outerHTML(); $.each(json,function(k,row){ var preCompiled = templateString; $.each(row,function(k,v){ var tag = templateTagOpen+k+templateTagClose; if(regExps[tag]) preCompiled = preCompiled.replace(regExps[tag],v); }); compiled += preCompiled; }); $(contentArea).html(compiled); } return this; }, outerHTML:function(html){ //allow getter setter functionality if(html) return this.replaceWith(html); var clone = $(this[0]).clone()[0]; return $((clone.nodeName.toLowerCase() == 'tr'?'<table>':'<div>')).append(clone).html(); } }); })(jQuery);