jquery.tmpl.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /*!
  2. * jQuery Templates Plugin 1.0.0pre
  3. * http://github.com/jquery/jquery-tmpl
  4. * Requires jQuery 1.4.2
  5. *
  6. * Copyright Software Freedom Conservancy, Inc.
  7. * Dual licensed under the MIT or GPL Version 2 licenses.
  8. * http://jquery.org/license
  9. */
  10. (function( jQuery, undefined ){
  11. var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,
  12. newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];
  13. function newTmplItem( options, parentItem, fn, data ) {
  14. // Returns a template item data structure for a new rendered instance of a template (a 'template item').
  15. // The content field is a hierarchical array of strings and nested items (to be
  16. // removed and replaced by nodes field of dom elements, once inserted in DOM).
  17. var newItem = {
  18. data: data || (data === 0 || data === false) ? data : (parentItem ? parentItem.data : {}),
  19. _wrap: parentItem ? parentItem._wrap : null,
  20. tmpl: null,
  21. parent: parentItem || null,
  22. nodes: [],
  23. calls: tiCalls,
  24. nest: tiNest,
  25. wrap: tiWrap,
  26. html: tiHtml,
  27. update: tiUpdate
  28. };
  29. if ( options ) {
  30. jQuery.extend( newItem, options, { nodes: [], parent: parentItem });
  31. }
  32. if ( fn ) {
  33. // Build the hierarchical content to be used during insertion into DOM
  34. newItem.tmpl = fn;
  35. newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem );
  36. newItem.key = ++itemKey;
  37. // Keep track of new template item, until it is stored as jQuery Data on DOM element
  38. (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem;
  39. }
  40. return newItem;
  41. }
  42. // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core).
  43. jQuery.each({
  44. appendTo: "append",
  45. prependTo: "prepend",
  46. insertBefore: "before",
  47. insertAfter: "after",
  48. replaceAll: "replaceWith"
  49. }, function( name, original ) {
  50. jQuery.fn[ name ] = function( selector ) {
  51. var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems,
  52. 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] );
  56. ret = this;
  57. } else {
  58. for ( i = 0, l = insert.length; i < l; i++ ) {
  59. cloneIndex = i;
  60. elems = (i > 0 ? this.clone(true) : this).get();
  61. jQuery( insert[i] )[ original ]( elems );
  62. ret = ret.concat( elems );
  63. }
  64. cloneIndex = 0;
  65. ret = this.pushStack( ret, name, insert.selector );
  66. }
  67. tmplItems = appendToTmplItems;
  68. appendToTmplItems = null;
  69. jQuery.tmpl.complete( tmplItems );
  70. return ret;
  71. };
  72. });
  73. jQuery.fn.extend({
  74. // Use first wrapped element as template markup.
  75. // Return wrapped set of template items, obtained by rendering template against data.
  76. tmpl: function( data, options, parentItem ) {
  77. return jQuery.tmpl( this[0], data, options, parentItem );
  78. },
  79. // Find which rendered template item the first wrapped DOM element belongs to
  80. tmplItem: function() {
  81. return jQuery.tmplItem( this[0] );
  82. },
  83. // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template.
  84. template: function( name ) {
  85. return jQuery.template( name, this[0] );
  86. },
  87. domManip: function( args, table, callback, options ) {
  88. if ( args[0] && jQuery.isArray( args[0] )) {
  89. var dmArgs = jQuery.makeArray( arguments ), elems = args[0], elemsLength = elems.length, i = 0, tmplItem;
  90. while ( i < elemsLength && !(tmplItem = jQuery.data( elems[i++], "tmplItem" ))) {}
  91. if ( tmplItem && cloneIndex ) {
  92. dmArgs[2] = function( fragClone ) {
  93. // Handler called by oldManip when rendered template has been inserted into DOM.
  94. jQuery.tmpl.afterManip( this, fragClone, callback );
  95. };
  96. }
  97. oldManip.apply( this, dmArgs );
  98. } else {
  99. oldManip.apply( this, arguments );
  100. }
  101. cloneIndex = 0;
  102. if ( !appendToTmplItems ) {
  103. jQuery.tmpl.complete( newTmplItems );
  104. }
  105. return this;
  106. }
  107. });
  108. jQuery.extend({
  109. // Return wrapped set of template items, obtained by rendering template against data.
  110. tmpl: function( tmpl, data, options, parentItem ) {
  111. var ret, topLevel = !parentItem;
  112. if ( topLevel ) {
  113. // This is a top-level tmpl call (not from a nested template using {{tmpl}})
  114. parentItem = topTmplItem;
  115. tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl );
  116. wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
  117. } else if ( !tmpl ) {
  118. // The template item is already associated with DOM - this is a refresh.
  119. // Re-evaluate rendered template for the parentItem
  120. tmpl = parentItem.tmpl;
  121. newTmplItems[parentItem.key] = parentItem;
  122. parentItem.nodes = [];
  123. if ( parentItem.wrapped ) {
  124. updateWrapped( parentItem, parentItem.wrapped );
  125. }
  126. // Rebuild, without creating a new template item
  127. return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) ));
  128. }
  129. if ( !tmpl ) {
  130. return []; // Could throw...
  131. }
  132. if ( typeof data === "function" ) {
  133. data = data.call( parentItem || {} );
  134. }
  135. if ( options && options.wrapped ) {
  136. updateWrapped( options, options.wrapped );
  137. }
  138. ret = jQuery.isArray( data ) ?
  139. jQuery.map( data, function( dataItem ) {
  140. return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
  141. }) :
  142. [ newTmplItem( options, parentItem, tmpl, data ) ];
  143. return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
  144. },
  145. // Return rendered template item for an element.
  146. tmplItem: function( elem ) {
  147. var tmplItem;
  148. if ( elem instanceof jQuery ) {
  149. elem = elem[0];
  150. }
  151. while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {}
  152. return tmplItem || topTmplItem;
  153. },
  154. // Set:
  155. // Use $.template( name, tmpl ) to cache a named template,
  156. // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc.
  157. // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration.
  158. // Get:
  159. // Use $.template( name ) to access a cached template.
  160. // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString )
  161. // will return the compiled template, without adding a name reference.
  162. // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent
  163. // to $.template( null, templateString )
  164. template: function( name, tmpl ) {
  165. if (tmpl) {
  166. // Compile template and associate with name
  167. if ( typeof tmpl === "string" ) {
  168. // This is an HTML string being passed directly in.
  169. tmpl = buildTmplFn( tmpl );
  170. } else if ( tmpl instanceof jQuery ) {
  171. tmpl = tmpl[0] || {};
  172. }
  173. if ( tmpl.nodeType ) {
  174. // If this is a template block, use cached copy, or generate tmpl function and cache.
  175. tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML ));
  176. // Issue: In IE, if the container element is not a script block, the innerHTML will remove quotes from attribute values whenever the value does not include white space.
  177. // This means that foo="${x}" will not work if the value of x includes white space: foo="${x}" -> foo=value of x.
  178. // To correct this, include space in tag: foo="${ x }" -> foo="value of x"
  179. }
  180. return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl;
  181. }
  182. // Return named compiled template
  183. return name ? (typeof name !== "string" ? jQuery.template( null, name ):
  184. (jQuery.template[name] ||
  185. // If not in map, and not containing at least on HTML tag, treat as a selector.
  186. // (If integrated with core, use quickExpr.exec)
  187. jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null;
  188. },
  189. encode: function( text ) {
  190. // Do HTML encoding replacing < > & and ' and " by corresponding entities.
  191. return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
  192. }
  193. });
  194. jQuery.extend( jQuery.tmpl, {
  195. tag: {
  196. "tmpl": {
  197. _default: { $2: "null" },
  198. open: "if($notnull_1){__=__.concat($item.nest($1,$2));}"
  199. // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions)
  200. // This means that {{tmpl foo}} treats foo as a template (which IS a function).
  201. // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}.
  202. },
  203. "wrap": {
  204. _default: { $2: "null" },
  205. open: "$item.calls(__,$1,$2);__=[];",
  206. close: "call=$item.calls();__=call._.concat($item.wrap(call,__));"
  207. },
  208. "each": {
  209. _default: { $2: "$index, $value" },
  210. open: "if($notnull_1){$.each($1a,function($2){with(this){",
  211. close: "}});}"
  212. },
  213. "if": {
  214. open: "if(($notnull_1) && $1a){",
  215. close: "}"
  216. },
  217. "else": {
  218. _default: { $1: "true" },
  219. open: "}else if(($notnull_1) && $1a){"
  220. },
  221. "html": {
  222. // Unecoded expression evaluation.
  223. open: "if($notnull_1){__.push($1a);}"
  224. },
  225. "=": {
  226. // Encoded expression evaluation. Abbreviated form is ${}.
  227. _default: { $1: "$data" },
  228. open: "if($notnull_1){__.push($.encode($1a));}"
  229. },
  230. "!": {
  231. // Comment tag. Skipped by parser
  232. open: ""
  233. }
  234. },
  235. // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events
  236. complete: function( items ) {
  237. newTmplItems = {};
  238. },
  239. // Call this from code which overrides domManip, or equivalent
  240. // Manage cloning/storing template items etc.
  241. afterManip: function afterManip( elem, fragClone, callback ) {
  242. // Provides cloned fragment ready for fixup prior to and after insertion into DOM
  243. var content = fragClone.nodeType === 11 ?
  244. jQuery.makeArray(fragClone.childNodes) :
  245. fragClone.nodeType === 1 ? [fragClone] : [];
  246. // Return fragment to original caller (e.g. append) for DOM insertion
  247. callback.call( elem, fragClone );
  248. // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
  249. storeTmplItems( content );
  250. cloneIndex++;
  251. }
  252. });
  253. //========================== Private helper functions, used by code above ==========================
  254. function build( tmplItem, nested, content ) {
  255. // Convert hierarchical content into flat string array
  256. // and finally return array of fragments ready for DOM insertion
  257. var frag, ret = content ? jQuery.map( content, function( item ) {
  258. return (typeof item === "string") ?
  259. // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM.
  260. (tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) :
  261. // This is a child template item. Build nested template.
  262. build( item, tmplItem, item._ctnt );
  263. }) :
  264. // 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()}}.
  265. tmplItem;
  266. if ( nested ) {
  267. return ret;
  268. }
  269. // top-level template
  270. ret = ret.join("");
  271. // Support templates which have initial or final text nodes, or consist only of text
  272. // Also support HTML entities within the HTML markup.
  273. ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) {
  274. frag = jQuery( middle ).get();
  275. storeTmplItems( frag );
  276. if ( before ) {
  277. frag = unencode( before ).concat(frag);
  278. }
  279. if ( after ) {
  280. frag = frag.concat(unencode( after ));
  281. }
  282. });
  283. return frag ? frag : unencode( ret );
  284. }
  285. function unencode( text ) {
  286. // Use createElement, since createTextNode will not render HTML entities correctly
  287. var el = document.createElement( "div" );
  288. el.innerHTML = text;
  289. return jQuery.makeArray(el.childNodes);
  290. }
  291. // Generate a reusable function that will serve to render a template against data
  292. function buildTmplFn( markup ) {
  293. return new Function("jQuery","$item",
  294. // Use the variable __ to hold a string array while building the compiled template. (See https://github.com/jquery/jquery-tmpl/issues#issue/10).
  295. "var $=jQuery,call,__=[],$data=$item.data;" +
  296. // Introduce the data as local variables using with(){}
  297. "with($data){__.push('" +
  298. // Convert the template into pure JavaScript
  299. jQuery.trim(markup)
  300. .replace( /([\\'])/g, "\\$1" )
  301. .replace( /[\r\t\n]/g, " " )
  302. .replace( /\$\{([^\}]*)\}/g, "{{= $1}}" )
  303. .replace( /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,
  304. function( all, slash, type, fnargs, target, parens, args ) {
  305. var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect;
  306. if ( !tag ) {
  307. throw "Unknown template tag: " + type;
  308. }
  309. def = tag._default || [];
  310. if ( parens && !/\w$/.test(target)) {
  311. target += parens;
  312. parens = "";
  313. }
  314. if ( target ) {
  315. target = unescape( target );
  316. args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : "");
  317. // Support for target being things like a.toLowerCase();
  318. // In that case don't call with template item as 'this' pointer. Just evaluate...
  319. expr = parens ? (target.indexOf(".") > -1 ? target + unescape( parens ) : ("(" + target + ").call($item" + args)) : target;
  320. exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))";
  321. } else {
  322. exprAutoFnDetect = expr = def.$1 || "null";
  323. }
  324. fnargs = unescape( fnargs );
  325. return "');" +
  326. tag[ slash ? "close" : "open" ]
  327. .split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" )
  328. .split( "$1a" ).join( exprAutoFnDetect )
  329. .split( "$1" ).join( expr )
  330. .split( "$2" ).join( fnargs || def.$2 || "" ) +
  331. "__.push('";
  332. }) +
  333. "');}return __;"
  334. );
  335. }
  336. function updateWrapped( options, wrapped ) {
  337. // Build the wrapped content.
  338. options._wrap = build( options, true,
  339. // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string.
  340. jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()]
  341. ).join("");
  342. }
  343. function unescape( args ) {
  344. return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null;
  345. }
  346. function outerHtml( elem ) {
  347. var div = document.createElement("div");
  348. div.appendChild( elem.cloneNode(true) );
  349. return div.innerHTML;
  350. }
  351. // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance.
  352. function storeTmplItems( content ) {
  353. var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m;
  354. for ( i = 0, l = content.length; i < l; i++ ) {
  355. if ( (elem = content[i]).nodeType !== 1 ) {
  356. continue;
  357. }
  358. elems = elem.getElementsByTagName("*");
  359. for ( m = elems.length - 1; m >= 0; m-- ) {
  360. processItemKey( elems[m] );
  361. }
  362. processItemKey( elem );
  363. }
  364. function processItemKey( el ) {
  365. var pntKey, pntNode = el, pntItem, tmplItem, key;
  366. // Ensure that each rendered template inserted into the DOM has its own template item,
  367. if ( (key = el.getAttribute( tmplItmAtt ))) {
  368. while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { }
  369. if ( pntKey !== key ) {
  370. // The next ancestor with a _tmplitem expando is on a different key than this one.
  371. // So this is a top-level element within this template item
  372. // Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment.
  373. pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0;
  374. if ( !(tmplItem = newTmplItems[key]) ) {
  375. // The item is for wrapped content, and was copied from the temporary parent wrappedItem.
  376. tmplItem = wrappedItems[key];
  377. tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode] );
  378. tmplItem.key = ++itemKey;
  379. newTmplItems[itemKey] = tmplItem;
  380. }
  381. if ( cloneIndex ) {
  382. cloneTmplItem( key );
  383. }
  384. }
  385. el.removeAttribute( tmplItmAtt );
  386. } else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) {
  387. // This was a rendered element, cloned during append or appendTo etc.
  388. // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem.
  389. cloneTmplItem( tmplItem.key );
  390. newTmplItems[tmplItem.key] = tmplItem;
  391. pntNode = jQuery.data( el.parentNode, "tmplItem" );
  392. pntNode = pntNode ? pntNode.key : 0;
  393. }
  394. if ( tmplItem ) {
  395. pntItem = tmplItem;
  396. // Find the template item of the parent element.
  397. // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string)
  398. while ( pntItem && pntItem.key != pntNode ) {
  399. // Add this element as a top-level node for this rendered template item, as well as for any
  400. // ancestor items between this item and the item of its parent element
  401. pntItem.nodes.push( el );
  402. pntItem = pntItem.parent;
  403. }
  404. // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering...
  405. delete tmplItem._ctnt;
  406. delete tmplItem._wrap;
  407. // Store template item as jQuery data on the element
  408. jQuery.data( el, "tmplItem", tmplItem );
  409. }
  410. function cloneTmplItem( key ) {
  411. key = key + keySuffix;
  412. tmplItem = newClonedItems[key] =
  413. (newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent ));
  414. }
  415. }
  416. }
  417. //---- Helper functions for template item ----
  418. function tiCalls( content, tmpl, data, options ) {
  419. if ( !content ) {
  420. return stack.pop();
  421. }
  422. stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options });
  423. }
  424. function tiNest( tmpl, data, options ) {
  425. // nested template, using {{tmpl}} tag
  426. return jQuery.tmpl( jQuery.template( tmpl ), data, options, this );
  427. }
  428. function tiWrap( call, wrapped ) {
  429. // nested template, using {{wrap}} tag
  430. var options = call.options || {};
  431. options.wrapped = wrapped;
  432. // Apply the template, which may incorporate wrapped content,
  433. return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item );
  434. }
  435. function tiHtml( filter, textOnly ) {
  436. var wrapped = this._wrap;
  437. return jQuery.map(
  438. jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ),
  439. function(e) {
  440. return textOnly ?
  441. e.innerText || e.textContent :
  442. e.outerHTML || outerHtml(e);
  443. });
  444. }
  445. function tiUpdate() {
  446. var coll = this.nodes;
  447. jQuery.tmpl( null, null, null, this).insertBefore( coll[0] );
  448. jQuery( coll ).remove();
  449. }
  450. })( jQuery );