API Docs for: 3.8.0
Show:

File: template/js/template-micro.js

  1. /**
  2. Adds the `Y.Template.Micro` template engine, which provides fast, simple
  3. string-based micro-templating similar to ERB or Underscore templates.

  4. @module template
  5. @submodule template-micro
  6. @since 3.8.0
  7. **/

  8. /**
  9. Fast, simple string-based micro-templating engine similar to ERB or Underscore
  10. templates.

  11. @class Template.Micro
  12. @static
  13. @since 3.8.0
  14. **/

  15. // This code was heavily inspired by Underscore.js's _.template() method
  16. // (written by Jeremy Ashkenas), which was in turn inspired by John Resig's
  17. // micro-templating implementation.

  18. var Micro = Y.namespace('Template.Micro');

  19. /**
  20. Default options for `Y.Template.Micro`.

  21. @property {Object} options

  22.     @param {RegExp} [options.code] Regex that matches code blocks like
  23.         `<% ... %>`.
  24.     @param {RegExp} [options.escapedOutput] Regex that matches escaped output
  25.         tags like `<%= ... %>`.
  26.     @param {RegExp} [options.rawOutput] Regex that matches raw output tags like
  27.         `<%== ... %>`.
  28.     @param {RegExp} [options.stringEscape] Regex that matches characters that
  29.         need to be escaped inside single-quoted JavaScript string literals.

  30. @static
  31. @since 3.8.0
  32. **/
  33. Micro.options = {
  34.     code         : /<%([\s\S]+?)%>/g,
  35.     escapedOutput: /<%=([\s\S]+?)%>/g,
  36.     rawOutput    : /<%==([\s\S]+?)%>/g,
  37.     stringEscape : /\\|'|\r|\n|\t|\u2028|\u2029/g
  38. };

  39. /**
  40. Compiles a template string into a JavaScript function. Pass a data object to the
  41. function to render the template using the given data and get back a rendered
  42. string.

  43. Within a template, use `<%= ... %>` to output the value of an expression (where
  44. `...` is the JavaScript expression or data variable to evaluate). The output
  45. will be HTML-escaped by default. To output a raw value without escaping, use
  46. `<%== ... %>`, but be careful not to do this with untrusted user input.

  47. To execute arbitrary JavaScript code within the template without rendering its
  48. output, use `<% ... %>`, where `...` is the code to be executed. This allows the
  49. use of if/else blocks, loops, function calls, etc., although it's recommended
  50. that you avoid embedding anything beyond basic flow control logic in your
  51. templates.

  52. Properties of the data object passed to a template function are made available
  53. on a `data` variable within the scope of the template. So, if you pass in
  54. the object `{message: 'hello!'}`, you can print the value of the `message`
  55. property using `<%= data.message %>`.

  56. @example

  57.     YUI().use('template-micro', function (Y) {
  58.         var template = '<ul class="<%= data.classNames.list %>">' +
  59.                            '<% Y.Array.each(data.items, function (item) { %>' +
  60.                                '<li><%= item %></li>' +
  61.                            '<% }); %>' +
  62.                        '</ul>';

  63.         // Compile the template into a function.
  64.         var compiled = Y.Template.Micro.compile(template);

  65.         // Render the template to HTML, passing in the data to use.
  66.         var html = compiled({
  67.             classNames: {list: 'demo'},
  68.             items     : ['one', 'two', 'three', 'four']
  69.         });
  70.     });

  71. @method compile
  72. @param {String} text Template text to compile.
  73. @param {Object} [options] Options. If specified, these options will override the
  74.     default options defined in `Y.Template.Micro.options`. See the documentation
  75.     for that property for details on which options are available.
  76. @return {Function} Compiled template function. Execute this function and pass in
  77.     a data object to render the template with the given data.
  78. @static
  79. @since 3.8.0
  80. **/
  81. Micro.compile = function (text, options) {
  82.     var blocks     = [],
  83.         tokenClose = "\uffff",
  84.         tokenOpen  = "\ufffe",
  85.         source;

  86.     options = Y.merge(Micro.options, options);

  87.     // Parse the input text into a string of JavaScript code, with placeholders
  88.     // for code blocks. Text outside of code blocks will be escaped for safe
  89.     // usage within a double-quoted string literal.
  90.     source = "var $b='',$t='" +

  91.         // U+FFFE and U+FFFF are guaranteed to represent non-characters, so no
  92.         // valid UTF-8 string should ever contain them. That means we can freely
  93.         // strip them out of the input text (just to be safe) and then use them
  94.         // for our own nefarious purposes as token placeholders!
  95.         //
  96.         // See http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Noncharacters
  97.         text.replace(/\ufffe|\uffff/g, '')

  98.         .replace(options.rawOutput, function (match, code) {
  99.             return tokenOpen + (blocks.push("'+\n((" + code + ")||$b)+\n'") - 1) + tokenClose;
  100.         })

  101.         .replace(options.escapedOutput, function (match, code) {
  102.             return tokenOpen + (blocks.push("'+\n$e((" + code + ")||$b)+\n'") - 1) + tokenClose;
  103.         })

  104.         .replace(options.code, function (match, code) {
  105.             return tokenOpen + (blocks.push("';\n" + code + "\n$t+='") - 1) + tokenClose;
  106.         })

  107.         .replace(options.stringEscape, "\\$&")

  108.         // Replace the token placeholders with code.
  109.         .replace(/\ufffe(\d+)\uffff/g, function (match, index) {
  110.             return blocks[parseInt(index, 10)];
  111.         })

  112.         // Remove noop string concatenations that have been left behind.
  113.         .replace(/\n\$t\+='';\n/g, '\n') +

  114.         "';\nreturn $t;";

  115.     // If compile() was called from precompile(), return precompiled source.
  116.     if (options.precompile) {
  117.         return "function (Y, $e, data) {\n" + source + "\n}";
  118.     }

  119.     // Otherwise, return an executable function.
  120.     return this.revive(new Function('Y', '$e', 'data', source));
  121. };

  122. /**
  123. Precompiles the given template text into a string of JavaScript source code that
  124. can be evaluated later in another context (or on another machine) to render the
  125. template.

  126. A common use case is to precompile templates at build time or on the server,
  127. then evaluate the code on the client to render a template. The client only needs
  128. to revive and render the template, avoiding the work of the compilation step.

  129. @method precompile
  130. @param {String} text Template text to precompile.
  131. @param {Object} [options] Options. If specified, these options will override the
  132.     default options defined in `Y.Template.Micro.options`. See the documentation
  133.     for that property for details on which options are available.
  134. @return {String} Source code for the precompiled template.
  135. @static
  136. @since 3.8.0
  137. **/
  138. Micro.precompile = function (text, options) {
  139.     options || (options = {});
  140.     options.precompile = true;

  141.     return this.compile(text, options);
  142. };

  143. /**
  144. Compiles and renders the given template text in a single step.

  145. This can be useful for single-use templates, but if you plan to render the same
  146. template multiple times, it's much better to use `compile()` to compile it once,
  147. then simply call the compiled function multiple times to avoid recompiling.

  148. @method render
  149. @param {String} text Template text to render.
  150. @param {Object} data Data to pass to the template.
  151. @param {Object} [options] Options. If specified, these options will override the
  152.     default options defined in `Y.Template.Micro.options`. See the documentation
  153.     for that property for details on which options are available.
  154. @return {String} Rendered result.
  155. @static
  156. @since 3.8.0
  157. **/
  158. Micro.render = function (text, data, options) {
  159.     return this.compile(text, options)(data);
  160. };

  161. /**
  162. Revives a precompiled template function into a normal compiled template function
  163. that can be called to render the template. The precompiled function must already
  164. have been evaluated to a function -- you can't pass raw JavaScript code to
  165. `revive()`.

  166. @method revive
  167. @param {Function} precompiled Precompiled template function.
  168. @return {Function} Revived template function, ready to be rendered.
  169. @static
  170. @since 3.8.0
  171. **/
  172. Micro.revive = function (precompiled) {
  173.     return function (data) {
  174.         data || (data = {});
  175.         return precompiled.call(data, Y, Y.Escape.html, data);
  176.     };
  177. };

  178.