Version 3.17.2
Show:

File: template/js/template-micro.js

  1. /*jshint expr:true */
  2.  
  3. /**
  4. Adds the `Y.Template.Micro` template engine, which provides fast, simple
  5. string-based micro-templating similar to ERB or Underscore templates.
  6.  
  7. @module template
  8. @submodule template-micro
  9. @since 3.8.0
  10. **/
  11.  
  12. /**
  13. Fast, simple string-based micro-templating engine similar to ERB or Underscore
  14. templates.
  15.  
  16. @class Template.Micro
  17. @static
  18. @since 3.8.0
  19. **/
  20.  
  21. // This code was heavily inspired by Underscore.js's _.template() method
  22. // (written by Jeremy Ashkenas), which was in turn inspired by John Resig's
  23. // micro-templating implementation.
  24.  
  25. var Micro = Y.namespace('Template.Micro');
  26.  
  27. /**
  28. Default options for `Y.Template.Micro`.
  29.  
  30. @property {Object} options
  31.  
  32. @param {RegExp} [options.code] Regex that matches code blocks like
  33. `<% ... %>`.
  34. @param {RegExp} [options.escapedOutput] Regex that matches escaped output
  35. tags like `<%= ... %>`.
  36. @param {RegExp} [options.rawOutput] Regex that matches raw output tags like
  37. `<%== ... %>`.
  38. @param {RegExp} [options.stringEscape] Regex that matches characters that
  39. need to be escaped inside single-quoted JavaScript string literals.
  40. @param {Object} [options.stringReplace] Hash that maps characters matched by
  41. `stringEscape` to the strings they should be replaced with. If you add
  42. a character to the `stringEscape` regex, you need to add it here too or
  43. it will be replaced with an empty string.
  44.  
  45. @static
  46. @since 3.8.0
  47. **/
  48. Micro.options = {
  49. code : /<%([\s\S]+?)%>/g,
  50. escapedOutput: /<%=([\s\S]+?)%>/g,
  51. rawOutput : /<%==([\s\S]+?)%>/g,
  52. stringEscape : /\\|'|\r|\n|\t|\u2028|\u2029/g,
  53.  
  54. stringReplace: {
  55. '\\' : '\\\\',
  56. "'" : "\\'",
  57. '\r' : '\\r',
  58. '\n' : '\\n',
  59. '\t' : '\\t',
  60. '\u2028': '\\u2028',
  61. '\u2029': '\\u2029'
  62. }
  63. };
  64.  
  65. /**
  66. Compiles a template string into a JavaScript function. Pass a data object to the
  67. function to render the template using the given data and get back a rendered
  68. string.
  69.  
  70. Within a template, use `<%= ... %>` to output the value of an expression (where
  71. `...` is the JavaScript expression or data variable to evaluate). The output
  72. will be HTML-escaped by default. To output a raw value without escaping, use
  73. `<%== ... %>`, but be careful not to do this with untrusted user input.
  74.  
  75. To execute arbitrary JavaScript code within the template without rendering its
  76. output, use `<% ... %>`, where `...` is the code to be executed. This allows the
  77. use of if/else blocks, loops, function calls, etc., although it's recommended
  78. that you avoid embedding anything beyond basic flow control logic in your
  79. templates.
  80.  
  81. Properties of the data object passed to a template function are made available
  82. on a `data` variable within the scope of the template. So, if you pass in
  83. the object `{message: 'hello!'}`, you can print the value of the `message`
  84. property using `<%= data.message %>`.
  85.  
  86. @example
  87.  
  88. YUI().use('template-micro', function (Y) {
  89. var template = '<ul class="<%= data.classNames.list %>">' +
  90. '<% Y.Array.each(data.items, function (item) { %>' +
  91. '<li><%= item %></li>' +
  92. '<% }); %>' +
  93. '</ul>';
  94.  
  95. // Compile the template into a function.
  96. var compiled = Y.Template.Micro.compile(template);
  97.  
  98. // Render the template to HTML, passing in the data to use.
  99. var html = compiled({
  100. classNames: {list: 'demo'},
  101. items : ['one', 'two', 'three', 'four']
  102. });
  103. });
  104.  
  105. @method compile
  106. @param {String} text Template text to compile.
  107. @param {Object} [options] Options. If specified, these options will override the
  108. default options defined in `Y.Template.Micro.options`. See the documentation
  109. for that property for details on which options are available.
  110. @return {Function} Compiled template function. Execute this function and pass in
  111. a data object to render the template with the given data.
  112. @static
  113. @since 3.8.0
  114. **/
  115. Micro.compile = function (text, options) {
  116. /*jshint evil:true */
  117.  
  118. var blocks = [],
  119. tokenClose = "\uffff",
  120. tokenOpen = "\ufffe",
  121. source;
  122.  
  123. options = Y.merge(Micro.options, options);
  124.  
  125. // Parse the input text into a string of JavaScript code, with placeholders
  126. // for code blocks. Text outside of code blocks will be escaped for safe
  127. // usage within a double-quoted string literal.
  128. //
  129. // $b is a blank string, used to avoid creating lots of string objects.
  130. //
  131. // $v is a function that returns the supplied value if the value is truthy
  132. // or the number 0, or returns an empty string if the value is falsy and not
  133. // 0.
  134. //
  135. // $t is the template string.
  136. source = "var $b='', $v=function (v){return v || v === 0 ? v : $b;}, $t='" +
  137.  
  138. // U+FFFE and U+FFFF are guaranteed to represent non-characters, so no
  139. // valid UTF-8 string should ever contain them. That means we can freely
  140. // strip them out of the input text (just to be safe) and then use them
  141. // for our own nefarious purposes as token placeholders!
  142. //
  143. // See http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Noncharacters
  144. text.replace(/\ufffe|\uffff/g, '')
  145.  
  146. .replace(options.rawOutput, function (match, code) {
  147. return tokenOpen + (blocks.push("'+\n$v(" + code + ")+\n'") - 1) + tokenClose;
  148. })
  149.  
  150. .replace(options.escapedOutput, function (match, code) {
  151. return tokenOpen + (blocks.push("'+\n$e($v(" + code + "))+\n'") - 1) + tokenClose;
  152. })
  153.  
  154. .replace(options.code, function (match, code) {
  155. return tokenOpen + (blocks.push("';\n" + code + "\n$t+='") - 1) + tokenClose;
  156. })
  157.  
  158. .replace(options.stringEscape, function (match) {
  159. return options.stringReplace[match] || '';
  160. })
  161.  
  162. // Replace the token placeholders with code.
  163. .replace(/\ufffe(\d+)\uffff/g, function (match, index) {
  164. return blocks[parseInt(index, 10)];
  165. })
  166.  
  167. // Remove noop string concatenations that have been left behind.
  168. .replace(/\n\$t\+='';\n/g, '\n') +
  169.  
  170. "';\nreturn $t;";
  171.  
  172. // If compile() was called from precompile(), return precompiled source.
  173. if (options.precompile) {
  174. return "function (Y, $e, data) {\n" + source + "\n}";
  175. }
  176.  
  177. // Otherwise, return an executable function.
  178. return this.revive(new Function('Y', '$e', 'data', source));
  179. };
  180.  
  181. /**
  182. Precompiles the given template text into a string of JavaScript source code that
  183. can be evaluated later in another context (or on another machine) to render the
  184. template.
  185.  
  186. A common use case is to precompile templates at build time or on the server,
  187. then evaluate the code on the client to render a template. The client only needs
  188. to revive and render the template, avoiding the work of the compilation step.
  189.  
  190. @method precompile
  191. @param {String} text Template text to precompile.
  192. @param {Object} [options] Options. If specified, these options will override the
  193. default options defined in `Y.Template.Micro.options`. See the documentation
  194. for that property for details on which options are available.
  195. @return {String} Source code for the precompiled template.
  196. @static
  197. @since 3.8.0
  198. **/
  199. Micro.precompile = function (text, options) {
  200. options || (options = {});
  201. options.precompile = true;
  202.  
  203. return this.compile(text, options);
  204. };
  205.  
  206. /**
  207. Compiles and renders the given template text in a single step.
  208.  
  209. This can be useful for single-use templates, but if you plan to render the same
  210. template multiple times, it's much better to use `compile()` to compile it once,
  211. then simply call the compiled function multiple times to avoid recompiling.
  212.  
  213. @method render
  214. @param {String} text Template text to render.
  215. @param {Object} data Data to pass to the template.
  216. @param {Object} [options] Options. If specified, these options will override the
  217. default options defined in `Y.Template.Micro.options`. See the documentation
  218. for that property for details on which options are available.
  219. @return {String} Rendered result.
  220. @static
  221. @since 3.8.0
  222. **/
  223. Micro.render = function (text, data, options) {
  224. return this.compile(text, options)(data);
  225. };
  226.  
  227. /**
  228. Revives a precompiled template function into a normal compiled template function
  229. that can be called to render the template. The precompiled function must already
  230. have been evaluated to a function -- you can't pass raw JavaScript code to
  231. `revive()`.
  232.  
  233. @method revive
  234. @param {Function} precompiled Precompiled template function.
  235. @return {Function} Revived template function, ready to be rendered.
  236. @static
  237. @since 3.8.0
  238. **/
  239. Micro.revive = function (precompiled) {
  240. return function (data) {
  241. data || (data = {});
  242. return precompiled.call(data, Y, Y.Escape.html, data);
  243. };
  244. };
  245.