Template.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /**
  2. * Represents an HTML fragment template. Templates may be {@link #compile precompiled} for greater performance.
  3. *
  4. * An instance of this class may be created by passing to the constructor either a single argument, or multiple
  5. * arguments:
  6. *
  7. * # Single argument: String/Array
  8. *
  9. * The single argument may be either a String or an Array:
  10. *
  11. * - String:
  12. *
  13. * var t = new Ext.Template("<div>Hello {0}.</div>");
  14. * t.{@link #append}('some-element', ['foo']);
  15. *
  16. * - Array:
  17. *
  18. * An Array will be combined with `join('')`.
  19. *
  20. * var t = new Ext.Template([
  21. * '<div name="{id}">',
  22. * '<span class="{cls}">{name:trim} {value:ellipsis(10)}</span>',
  23. * '</div>',
  24. * ]);
  25. * t.{@link #compile}();
  26. * t.{@link #append}('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
  27. *
  28. * # Multiple arguments: String, Object, Array, ...
  29. *
  30. * Multiple arguments will be combined with `join('')`.
  31. *
  32. * var t = new Ext.Template(
  33. * '<div name="{id}">',
  34. * '<span class="{cls}">{name} {value}</span>',
  35. * '</div>',
  36. * // a configuration object:
  37. * {
  38. * compiled: true, // {@link #compile} immediately
  39. * }
  40. * );
  41. *
  42. * # Notes
  43. *
  44. * - For a list of available format functions, see {@link Ext.util.Format}.
  45. * - `disableFormats` reduces `{@link #apply}` time when no formatting is required.
  46. */
  47. Ext.define('Ext.Template', {
  48. /* Begin Definitions */
  49. requires: ['Ext.dom.Helper', 'Ext.util.Format'],
  50. inheritableStatics: {
  51. /**
  52. * Creates a template from the passed element's value (_display:none_ textarea, preferred) or innerHTML.
  53. * @param {String/HTMLElement} el A DOM element or its id
  54. * @param {Object} config (optional) Config object
  55. * @return {Ext.Template} The created template
  56. * @static
  57. * @inheritable
  58. */
  59. from: function(el, config) {
  60. el = Ext.getDom(el);
  61. return new this(el.value || el.innerHTML, config || '');
  62. }
  63. },
  64. /* End Definitions */
  65. /**
  66. * Creates new template.
  67. *
  68. * @param {String...} html List of strings to be concatenated into template.
  69. * Alternatively an array of strings can be given, but then no config object may be passed.
  70. * @param {Object} config (optional) Config object
  71. */
  72. constructor: function(html) {
  73. var me = this,
  74. args = arguments,
  75. buffer = [],
  76. i = 0,
  77. length = args.length,
  78. value;
  79. me.initialConfig = {};
  80. // Allow an array to be passed here so we can
  81. // pass an array of strings and an object
  82. // at the end
  83. if (length === 1 && Ext.isArray(html)) {
  84. args = html;
  85. length = args.length;
  86. }
  87. if (length > 1) {
  88. for (; i < length; i++) {
  89. value = args[i];
  90. if (typeof value == 'object') {
  91. Ext.apply(me.initialConfig, value);
  92. Ext.apply(me, value);
  93. } else {
  94. buffer.push(value);
  95. }
  96. }
  97. } else {
  98. buffer.push(html);
  99. }
  100. // @private
  101. me.html = buffer.join('');
  102. if (me.compiled) {
  103. me.compile();
  104. }
  105. },
  106. /**
  107. * @property {Boolean} isTemplate
  108. * `true` in this class to identify an object as an instantiated Template, or subclass thereof.
  109. */
  110. isTemplate: true,
  111. /**
  112. * @cfg {Boolean} compiled
  113. * True to immediately compile the template. Defaults to false.
  114. */
  115. /**
  116. * @cfg {Boolean} disableFormats
  117. * True to disable format functions in the template. If the template doesn't contain
  118. * format functions, setting disableFormats to true will reduce apply time. Defaults to false.
  119. */
  120. disableFormats: false,
  121. re: /\{([\w\-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
  122. /**
  123. * Returns an HTML fragment of this template with the specified values applied.
  124. *
  125. * @param {Object/Array} values The template values. Can be an array if your params are numeric:
  126. *
  127. * var tpl = new Ext.Template('Name: {0}, Age: {1}');
  128. * tpl.apply(['John', 25]);
  129. *
  130. * or an object:
  131. *
  132. * var tpl = new Ext.Template('Name: {name}, Age: {age}');
  133. * tpl.apply({name: 'John', age: 25});
  134. *
  135. * @return {String} The HTML fragment
  136. */
  137. apply: function(values) {
  138. var me = this,
  139. useFormat = me.disableFormats !== true,
  140. fm = Ext.util.Format,
  141. tpl = me,
  142. ret;
  143. if (me.compiled) {
  144. return me.compiled(values).join('');
  145. }
  146. function fn(m, name, format, args) {
  147. if (format && useFormat) {
  148. if (args) {
  149. args = [values[name]].concat(Ext.functionFactory('return ['+ args +'];')());
  150. } else {
  151. args = [values[name]];
  152. }
  153. if (format.substr(0, 5) == "this.") {
  154. return tpl[format.substr(5)].apply(tpl, args);
  155. }
  156. else {
  157. return fm[format].apply(fm, args);
  158. }
  159. }
  160. else {
  161. return values[name] !== undefined ? values[name] : "";
  162. }
  163. }
  164. ret = me.html.replace(me.re, fn);
  165. return ret;
  166. },
  167. /**
  168. * Appends the result of this template to the provided output array.
  169. * @param {Object/Array} values The template values. See {@link #apply}.
  170. * @param {Array} out The array to which output is pushed.
  171. * @return {Array} The given out array.
  172. */
  173. applyOut: function(values, out) {
  174. var me = this;
  175. if (me.compiled) {
  176. out.push.apply(out, me.compiled(values));
  177. } else {
  178. out.push(me.apply(values));
  179. }
  180. return out;
  181. },
  182. /**
  183. * @method applyTemplate
  184. * @member Ext.Template
  185. * Alias for {@link #apply}.
  186. * @inheritdoc Ext.Template#apply
  187. */
  188. applyTemplate: function () {
  189. return this.apply.apply(this, arguments);
  190. },
  191. /**
  192. * Sets the HTML used as the template and optionally compiles it.
  193. * @param {String} html
  194. * @param {Boolean} compile (optional) True to compile the template.
  195. * @return {Ext.Template} this
  196. */
  197. set: function(html, compile) {
  198. var me = this;
  199. me.html = html;
  200. me.compiled = null;
  201. return compile ? me.compile() : me;
  202. },
  203. compileARe: /\\/g,
  204. compileBRe: /(\r\n|\n)/g,
  205. compileCRe: /'/g,
  206. /**
  207. * Compiles the template into an internal function, eliminating the RegEx overhead.
  208. * @return {Ext.Template} this
  209. */
  210. compile: function() {
  211. var me = this,
  212. fm = Ext.util.Format,
  213. useFormat = me.disableFormats !== true,
  214. body, bodyReturn;
  215. function fn(m, name, format, args) {
  216. if (format && useFormat) {
  217. args = args ? ',' + args: "";
  218. if (format.substr(0, 5) != "this.") {
  219. format = "fm." + format + '(';
  220. }
  221. else {
  222. format = 'this.' + format.substr(5) + '(';
  223. }
  224. }
  225. else {
  226. args = '';
  227. format = "(values['" + name + "'] == undefined ? '' : ";
  228. }
  229. return "'," + format + "values['" + name + "']" + args + ") ,'";
  230. }
  231. bodyReturn = me.html.replace(me.compileARe, '\\\\').replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn);
  232. body = "this.compiled = function(values){ return ['" + bodyReturn + "'];};";
  233. eval(body);
  234. return me;
  235. },
  236. /**
  237. * Applies the supplied values to the template and inserts the new node(s) as the first child of el.
  238. *
  239. * @param {String/HTMLElement/Ext.Element} el The context element
  240. * @param {Object/Array} values The template values. See {@link #applyTemplate} for details.
  241. * @param {Boolean} returnElement (optional) true to return a Ext.Element.
  242. * @return {HTMLElement/Ext.Element} The new node or Element
  243. */
  244. insertFirst: function(el, values, returnElement) {
  245. return this.doInsert('afterBegin', el, values, returnElement);
  246. },
  247. /**
  248. * Applies the supplied values to the template and inserts the new node(s) before el.
  249. *
  250. * @param {String/HTMLElement/Ext.Element} el The context element
  251. * @param {Object/Array} values The template values. See {@link #applyTemplate} for details.
  252. * @param {Boolean} returnElement (optional) true to return a Ext.Element.
  253. * @return {HTMLElement/Ext.Element} The new node or Element
  254. */
  255. insertBefore: function(el, values, returnElement) {
  256. return this.doInsert('beforeBegin', el, values, returnElement);
  257. },
  258. /**
  259. * Applies the supplied values to the template and inserts the new node(s) after el.
  260. *
  261. * @param {String/HTMLElement/Ext.Element} el The context element
  262. * @param {Object/Array} values The template values. See {@link #applyTemplate} for details.
  263. * @param {Boolean} returnElement (optional) true to return a Ext.Element.
  264. * @return {HTMLElement/Ext.Element} The new node or Element
  265. */
  266. insertAfter: function(el, values, returnElement) {
  267. return this.doInsert('afterEnd', el, values, returnElement);
  268. },
  269. /**
  270. * Applies the supplied `values` to the template and appends the new node(s) to the specified `el`.
  271. *
  272. * For example usage see {@link Ext.Template Ext.Template class docs}.
  273. *
  274. * @param {String/HTMLElement/Ext.Element} el The context element
  275. * @param {Object/Array} values The template values. See {@link #applyTemplate} for details.
  276. * @param {Boolean} returnElement (optional) true to return an Ext.Element.
  277. * @return {HTMLElement/Ext.Element} The new node or Element
  278. */
  279. append: function(el, values, returnElement) {
  280. return this.doInsert('beforeEnd', el, values, returnElement);
  281. },
  282. doInsert: function(where, el, values, returnElement) {
  283. var newNode = Ext.DomHelper.insertHtml(where, Ext.getDom(el), this.apply(values));
  284. return returnElement ? Ext.get(newNode) : newNode;
  285. },
  286. /**
  287. * Applies the supplied values to the template and overwrites the content of el with the new node(s).
  288. *
  289. * @param {String/HTMLElement/Ext.Element} el The context element
  290. * @param {Object/Array} values The template values. See {@link #applyTemplate} for details.
  291. * @param {Boolean} returnElement (optional) true to return a Ext.Element.
  292. * @return {HTMLElement/Ext.Element} The new node or Element
  293. */
  294. overwrite: function(el, values, returnElement) {
  295. var newNode = Ext.DomHelper.overwrite(Ext.getDom(el), this.apply(values));
  296. return returnElement ? Ext.get(newNode) : newNode;
  297. }
  298. });