2 * Copy of http://github.com/nje/jquery-tmpl/raw/master/jquery.tmpl.js at f827fb68417bc14ab9f6ae889421d5fea4cb2859
3 * jQuery Templating Plugin
4 * Copyright 2010, John Resig
5 * Dual licensed under the MIT or GPL Version 2 licenses.
7 (function( jQuery, undefined ){
8 var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,
9 newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];
11 function newTmplItem( options, parentItem, fn, data ) {
12 // Returns a template item data structure for a new rendered instance of a template (a 'template item').
13 // The content field is a hierarchical array of strings and nested items (to be
14 // removed and replaced by nodes field of dom elements, once inserted in DOM).
16 data: data || (parentItem ? parentItem.data : {}),
17 _wrap: parentItem ? parentItem._wrap : null,
19 parent: parentItem || null,
28 jQuery.extend( newItem, options, { nodes: [], parent: parentItem } );
31 // Build the hierarchical content to be used during insertion into DOM
33 newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem );
34 newItem.key = ++itemKey;
35 // Keep track of new template item, until it is stored as jQuery Data on DOM element
36 (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem;
41 // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core).
45 insertBefore: "before",
47 replaceAll: "replaceWith"
48 }, function( name, original ) {
49 jQuery.fn[ name ] = function( selector ) {
50 var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems,
51 parent = this.length === 1 && this[0].parentNode;
53 appendToTmplItems = newTmplItems || {};
54 if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
55 insert[ original ]( this[0] );
58 for ( i = 0, l = insert.length; i < l; i++ ) {
60 elems = (i > 0 ? this.clone(true) : this).get();
61 jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
62 ret = ret.concat( elems );
65 ret = this.pushStack( ret, name, insert.selector );
67 tmplItems = appendToTmplItems;
68 appendToTmplItems = null;
69 jQuery.tmpl.complete( tmplItems );
75 // Use first wrapped element as template markup.
76 // Return wrapped set of template items, obtained by rendering template against data.
77 tmpl: function( data, options, parentItem ) {
78 return jQuery.tmpl( this[0], data, options, parentItem );
81 // Find which rendered template item the first wrapped DOM element belongs to
82 tmplItem: function() {
83 return jQuery.tmplItem( this[0] );
86 // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template.
87 template: function( name ) {
88 return jQuery.template( name, this[0] );
91 domManip: function( args, table, callback, options ) {
92 // This appears to be a bug in the appendTo, etc. implementation
93 // it should be doing .call() instead of .apply(). See #6227
94 if ( args[0] && args[0].nodeType ) {
95 var dmArgs = jQuery.makeArray( arguments ), argsLength = args.length, i = 0, tmplItem;
96 while ( i < argsLength && !(tmplItem = jQuery.data( args[i++], "tmplItem" ))) {}
97 if ( argsLength > 1 ) {
98 dmArgs[0] = [jQuery.makeArray( args )];
100 if ( tmplItem && cloneIndex ) {
101 dmArgs[2] = function( fragClone ) {
102 // Handler called by oldManip when rendered template has been inserted into DOM.
103 jQuery.tmpl.afterManip( this, fragClone, callback );
106 oldManip.apply( this, dmArgs );
108 oldManip.apply( this, arguments );
111 if ( !appendToTmplItems ) {
112 jQuery.tmpl.complete( newTmplItems );
119 // Return wrapped set of template items, obtained by rendering template against data.
120 tmpl: function( tmpl, data, options, parentItem ) {
121 var ret, topLevel = !parentItem;
123 // This is a top-level tmpl call (not from a nested template using {{tmpl}})
124 parentItem = topTmplItem;
125 tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl );
126 wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
127 } else if ( !tmpl ) {
128 // The template item is already associated with DOM - this is a refresh.
129 // Re-evaluate rendered template for the parentItem
130 tmpl = parentItem.tmpl;
131 newTmplItems[parentItem.key] = parentItem;
132 parentItem.nodes = [];
133 if ( parentItem.wrapped ) {
134 updateWrapped( parentItem, parentItem.wrapped );
136 // Rebuild, without creating a new template item
137 return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) ));
140 return []; // Could throw...
142 if ( typeof data === "function" ) {
143 data = data.call( parentItem || {} );
145 if ( options && options.wrapped ) {
146 updateWrapped( options, options.wrapped );
148 ret = jQuery.isArray( data ) ?
149 jQuery.map( data, function( dataItem ) {
150 return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
152 [ newTmplItem( options, parentItem, tmpl, data ) ];
154 return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
157 // Return rendered template item for an element.
158 tmplItem: function( elem ) {
160 if ( elem instanceof jQuery ) {
163 while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {}
164 return tmplItem || topTmplItem;
168 // Use $.template( name, tmpl ) to cache a named template,
169 // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc.
170 // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration.
173 // Use $.template( name ) to access a cached template.
174 // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString )
175 // will return the compiled template, without adding a name reference.
176 // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent
177 // to $.template( null, templateString )
178 template: function( name, tmpl ) {
180 // Compile template and associate with name
181 if ( typeof tmpl === "string" ) {
182 // This is an HTML string being passed directly in.
183 tmpl = buildTmplFn( tmpl )
184 } else if ( tmpl instanceof jQuery ) {
185 tmpl = tmpl[0] || {};
187 if ( tmpl.nodeType ) {
188 // If this is a template block, use cached copy, or generate tmpl function and cache.
189 tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML ));
191 return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl;
193 // Return named compiled template
194 return name ? (typeof name !== "string" ? jQuery.template( null, name ):
195 (jQuery.template[name] ||
196 // If not in map, treat as a selector. (If integrated with core, use quickExpr.exec)
197 jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null;
200 encode: function( text ) {
201 // Do HTML encoding replacing < > & and ' and " by corresponding entities.
202 return ("" + text).split("<").join("<").split(">").join(">").split('"').join(""").split("'").join("'");
206 jQuery.extend( jQuery.tmpl, {
209 _default: { $2: "null" },
210 open: "if($notnull_1){_=_.concat($item.nest($1,$2));}"
211 // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions)
212 // This means that {{tmpl foo}} treats foo as a template (which IS a function).
213 // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}.
216 _default: { $2: "null" },
217 open: "$item.calls(_,$1,$2);_=[];",
218 close: "call=$item.calls();_=call._.concat($item.wrap(call,_));"
221 _default: { $2: "$index, $value" },
222 open: "if($notnull_1){$.each($1a,function($2){with(this){",
226 open: "if(($notnull_1) && $1a){",
230 _default: { $1: "true" },
231 open: "}else if(($notnull_1) && $1a){"
234 // Unecoded expression evaluation.
235 open: "if($notnull_1){_.push($1a);}"
238 // Encoded expression evaluation. Abbreviated form is ${}.
239 _default: { $1: "$data" },
240 open: "if($notnull_1){_.push($.encode($1a));}"
243 // Comment tag. Skipped by parser
248 // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events
249 complete: function( items ) {
253 // Call this from code which overrides domManip, or equivalent
254 // Manage cloning/storing template items etc.
255 afterManip: function afterManip( elem, fragClone, callback ) {
256 // Provides cloned fragment ready for fixup prior to and after insertion into DOM
257 var content = fragClone.nodeType === 11 ?
258 jQuery.makeArray(fragClone.childNodes) :
259 fragClone.nodeType === 1 ? [fragClone] : [];
261 // Return fragment to original caller (e.g. append) for DOM insertion
262 callback.call( elem, fragClone );
264 // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
265 storeTmplItems( content );
270 //========================== Private helper functions, used by code above ==========================
272 function build( tmplItem, nested, content ) {
273 // Convert hierarchical content into flat string array
274 // and finally return array of fragments ready for DOM insertion
275 var frag, ret = content ? jQuery.map( content, function( item ) {
276 return (typeof item === "string") ?
277 // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM.
278 (tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) :
279 // This is a child template item. Build nested template.
280 build( item, tmplItem, item._ctnt );
282 // If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}.
288 // top-level template
291 // Support templates which have initial or final text nodes, or consist only of text
292 // Also support HTML entities within the HTML markup.
293 ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) {
294 frag = jQuery( middle ).get();
296 storeTmplItems( frag );
298 frag = unencode( before ).concat(frag);
301 frag = frag.concat(unencode( after ));
304 return frag ? frag : unencode( ret );
307 function unencode( text ) {
308 // Use createElement, since createTextNode will not render HTML entities correctly
309 var el = document.createElement( "div" );
311 return jQuery.makeArray(el.childNodes);
314 // Generate a reusable function that will serve to render a template against data
315 function buildTmplFn( markup ) {
316 return new Function("jQuery","$item",
317 "var $=jQuery,call,_=[],$data=$item.data;" +
319 // Introduce the data as local variables using with(){}
320 "with($data){_.push('" +
322 // Convert the template into pure JavaScript
324 .replace( /([\\'])/g, "\\$1" )
325 .replace( /[\r\t\n]/g, " " )
326 .replace( /\$\{([^\}]*)\}/g, "{{= $1}}" )
327 .replace( /\{\{(\/?)(\w+|.)(?:\(((?:.(?!\}\}))*?)?\))?(?:\s+(.*?)?)?(\((.*?)\))?\s*\}\}/g,
328 function( all, slash, type, fnargs, target, parens, args ) {
329 var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect;
331 throw "Template command not found: " + type;
333 def = tag._default || [];
334 if ( parens && !/\w$/.test(target)) {
339 target = unescape( target );
340 args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : "");
341 // Support for target being things like a.toLowerCase();
342 // In that case don't call with template item as 'this' pointer. Just evaluate...
343 expr = parens ? (target.indexOf(".") > -1 ? target + parens : ("(" + target + ").call($item" + args)) : target;
344 exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))";
346 exprAutoFnDetect = expr = def.$1 || "null";
348 fnargs = unescape( fnargs );
350 tag[ slash ? "close" : "open" ]
351 .split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" )
352 .split( "$1a" ).join( exprAutoFnDetect )
353 .split( "$1" ).join( expr )
354 .split( "$2" ).join( fnargs ?
355 fnargs.replace( /\s*([^\(]+)\s*(\((.*?)\))?/g, function( all, name, parens, params ) {
356 params = params ? ("," + params + ")") : (parens ? ")" : "");
357 return params ? ("(" + name + ").call($item" + params) : all;
366 function updateWrapped( options, wrapped ) {
367 // Build the wrapped content.
368 options._wrap = build( options, true,
369 // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string.
370 jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()]
374 function unescape( args ) {
375 return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null;
377 function outerHtml( elem ) {
378 var div = document.createElement("div");
379 div.appendChild( elem.cloneNode(true) );
380 return div.innerHTML;
383 // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance.
384 function storeTmplItems( content ) {
385 var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m;
386 for ( i = 0, l = content.length; i < l; i++ ) {
387 if ( (elem = content[i]).nodeType !== 1 ) {
390 elems = elem.getElementsByTagName("*");
391 for ( m = elems.length - 1; m >= 0; m-- ) {
392 processItemKey( elems[m] );
394 processItemKey( elem );
396 function processItemKey( el ) {
397 var pntKey, pntNode = el, pntItem, tmplItem, key;
398 // Ensure that each rendered template inserted into the DOM has its own template item,
399 if ( (key = el.getAttribute( tmplItmAtt ))) {
400 while ((pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { }
401 if ( pntKey !== key ) {
402 // The next ancestor with a _tmplitem expando is on a different key than this one.
403 // So this is a top-level element within this template item
404 pntNode = pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0);
405 if ( !(tmplItem = newTmplItems[key]) ) {
406 // The item is for wrapped content, and was copied from the temporary parent wrappedItem.
407 tmplItem = wrappedItems[key];
408 tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode], null, true );
409 tmplItem.key = ++itemKey;
410 newTmplItems[itemKey] = tmplItem;
413 cloneTmplItem( key );
416 el.removeAttribute( tmplItmAtt );
417 } else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) {
418 // This was a rendered element, cloned during append or appendTo etc.
419 // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem.
420 cloneTmplItem( tmplItem.key );
421 newTmplItems[tmplItem.key] = tmplItem;
422 pntNode = jQuery.data( el.parentNode, "tmplItem" );
423 pntNode = pntNode ? pntNode.key : 0;
427 // Find the template item of the parent element.
428 // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string)
429 while ( pntItem && pntItem.key != pntNode ) {
430 // Add this element as a top-level node for this rendered template item, as well as for any
431 // ancestor items between this item and the item of its parent element
432 pntItem.nodes.push( el );
433 pntItem = pntItem.parent;
435 // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering...
436 delete tmplItem._ctnt;
437 delete tmplItem._wrap;
438 // Store template item as jQuery data on the element
439 jQuery.data( el, "tmplItem", tmplItem );
441 function cloneTmplItem( key ) {
442 key = key + keySuffix;
443 tmplItem = newClonedItems[key] =
444 (newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent, null, true ));
449 //---- Helper functions for template item ----
451 function tiCalls( content, tmpl, data, options ) {
455 stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options });
458 function tiNest( tmpl, data, options ) {
459 // nested template, using {{tmpl}} tag
460 return jQuery.tmpl( jQuery.template( tmpl ), data, options, this );
463 function tiWrap( call, wrapped ) {
464 // nested template, using {{wrap}} tag
465 var options = call.options || {};
466 options.wrapped = wrapped;
467 // Apply the template, which may incorporate wrapped content,
468 return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item );
471 function tiHtml( filter, textOnly ) {
472 var wrapped = this._wrap;
474 jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ),
477 e.innerText || e.textContent :
478 e.outerHTML || outerHtml(e);
482 function tiUpdate() {
483 var coll = this.nodes;
484 jQuery.tmpl( null, null, null, this).insertBefore( coll[0] );
485 jQuery( coll ).remove();