jquery.tmpl.js 19 KB

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