Skip to content

Instantly share code, notes, and snippets.

@amasad
Created March 9, 2011 23:44
Show Gist options
  • Save amasad/863261 to your computer and use it in GitHub Desktop.
Save amasad/863261 to your computer and use it in GitHub Desktop.
Load external jquery templates and compile them on the fly
(function($){
$.extend({
loadTmpl: function(url, name, cb){
var c;
if (typeof name === "function"){
cb = name;
}else if(!cb){
cb = $.noop;
}
if ($.isArray(url)){
c = url.length;
$.each(url, function(i, o){
_load(o.url, o.name);
});
}else{
cb();
return _load(url, name);
}
function _load(u, n){
if (!n) n = u;
return $.get(u, function(d){
$.template(n, d);
if (c === 1){
cb();
}else if(c > 0){
c--;
}
});
}
}
});
})( jQuery );
/*
* loadTmpl: load external jquery templates
*
* $.loadTmpl( url [, [name,] callback])
* url: String url to load tmplate file from
* name: String name of the compiled template, to be accessed $.tmpl(name), if not found, url will be used.
* callback: Function to callback when the script is loaded and compiled
*
* example:
* $.loadTmpl('tmpls/row.tmpl', 'row', function(){
* $.tmpl('row', {name: "amjad masad"} ).appendTo('#myDiv');
* });
*
* $.loadTmpl('tmpls/row.tmpl').done(function(){
* $.tmpl('tmpls/row.tmpl').appendTo('#myDiv');
* });
*
*
* $.loadTmpl( array [,callback] )
* array: array of objects containing urls and optionally a name;
* array elements: {url: the url of the template file, name:the name of the compiled template}
* callback: called when all templates are retrieved and compiled
*
* example:
* $.loadTmpl( [{url: 'tmpl/row.tmpl', name: 'row'}, {url: 'tmpl/table.tmpl', name : 'table'}], function(){
* alert('done');
* $.tmpl('table').append($.tmpl('row')).appendTo('body');
* });
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment