Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

262 строки
7.1KB

  1. /*
  2. Shamless port of http://github.com/defunkt/mustache
  3. by Jan Lehnardt <jan@apache.org>, Alexander Lang <alex@upstream-berlin.com>,
  4. Sebastian Cohnen <sebastian.cohnen@googlemail.com>
  5. Thanks @defunkt for the awesome code.
  6. See http://github.com/defunkt/mustache for more info.
  7. */
  8. var Mustache = function() {
  9. var Renderer = function() {};
  10. Renderer.prototype = {
  11. otag: "{{",
  12. ctag: "}}",
  13. pragmas: {},
  14. render: function(template, context, partials) {
  15. // fail fast
  16. if(template.indexOf(this.otag) == -1) {
  17. return template;
  18. }
  19. template = this.render_pragmas(template);
  20. var html = this.render_section(template, context, partials);
  21. return this.render_tags(html, context, partials);
  22. },
  23. /*
  24. Looks for %PRAGMAS
  25. */
  26. render_pragmas: function(template) {
  27. // no pragmas
  28. if(template.indexOf(this.otag + "%") == -1) {
  29. return template;
  30. }
  31. var that = this;
  32. var regex = new RegExp(this.otag + "%(.+)" + this.ctag);
  33. return template.replace(regex, function(match, pragma) {
  34. that.pragmas[pragma] = true;
  35. return "";
  36. // ignore unknown pragmas silently
  37. });
  38. },
  39. /*
  40. Tries to find a partial in the global scope and render it
  41. */
  42. render_partial: function(name, context, partials) {
  43. if(typeof(context[name]) != "object") {
  44. throw({message: "subcontext for '" + name + "' is not an object"});
  45. }
  46. if(!partials || !partials[name]) {
  47. throw({message: "unknown_partial"});
  48. }
  49. return this.render(partials[name], context[name], partials);
  50. },
  51. /*
  52. Renders boolean and enumerable sections
  53. */
  54. render_section: function(template, context, partials) {
  55. if(template.indexOf(this.otag + "#") == -1) {
  56. return template;
  57. }
  58. var that = this;
  59. // CSW - Added "+?" so it finds the tighest bound, not the widest
  60. var regex = new RegExp(this.otag + "\\#(.+)" + this.ctag +
  61. "\\s*([\\s\\S]+?)" + this.otag + "\\/\\1" + this.ctag + "\\s*", "mg");
  62. // for each {{#foo}}{{/foo}} section do...
  63. return template.replace(regex, function(match, name, content) {
  64. var value = that.find(name, context);
  65. if(that.is_array(value)) { // Enumerable, Let's loop!
  66. return that.map(value, function(row) {
  67. return that.render(content, that.merge(context,
  68. that.create_context(row)), partials);
  69. }).join('');
  70. } else if(value) { // boolean section
  71. return that.render(content, context, partials);
  72. } else {
  73. return "";
  74. }
  75. });
  76. },
  77. /*
  78. Replace {{foo}} and friends with values from our view
  79. */
  80. render_tags: function(template, context, partials) {
  81. var lines = template.split("\n");
  82. var new_regex = function() {
  83. return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\/#]+?)\\1?" +
  84. that.ctag + "+", "g");
  85. };
  86. // tit for tat
  87. var that = this;
  88. var regex = new_regex();
  89. for (var i=0; i < lines.length; i++) {
  90. lines[i] = lines[i].replace(regex, function (match,operator,name) {
  91. switch(operator) {
  92. case "!": // ignore comments
  93. return match;
  94. case "=": // set new delimiters, rebuild the replace regexp
  95. that.set_delimiters(name);
  96. regex = new_regex();
  97. // redo the line in order to get tags with the new delimiters
  98. // on the same line
  99. i--;
  100. return "";
  101. case ">": // render partial
  102. return that.render_partial(name, context, partials);
  103. case "{": // the triple mustache is unescaped
  104. return that.find(name, context);
  105. return "";
  106. default: // escape the value
  107. return that.escape(that.find(name, context));
  108. }
  109. },this);
  110. };
  111. return lines.join("\n");
  112. },
  113. set_delimiters: function(delimiters) {
  114. var dels = delimiters.split(" ");
  115. this.otag = this.escape_regex(dels[0]);
  116. this.ctag = this.escape_regex(dels[1]);
  117. },
  118. escape_regex: function(text) {
  119. // thank you Simon Willison
  120. if(!arguments.callee.sRE) {
  121. var specials = [
  122. '/', '.', '*', '+', '?', '|',
  123. '(', ')', '[', ']', '{', '}', '\\'
  124. ];
  125. arguments.callee.sRE = new RegExp(
  126. '(\\' + specials.join('|\\') + ')', 'g'
  127. );
  128. }
  129. return text.replace(arguments.callee.sRE, '\\$1');
  130. },
  131. /*
  132. find `name` in current `context`. That is find me a value
  133. from the view object
  134. */
  135. find: function(name, context) {
  136. name = this.trim(name);
  137. if(typeof context[name] === "function") {
  138. return context[name].apply(context);
  139. }
  140. if(context[name] !== undefined) {
  141. return context[name];
  142. }
  143. // silently ignore unkown variables
  144. return "";
  145. },
  146. // Utility methods
  147. /*
  148. Does away with nasty characters
  149. */
  150. escape: function(s) {
  151. return s.toString().replace(/[&"<>\\]/g, function(s) {
  152. switch(s) {
  153. case "&": return "&amp;";
  154. case "\\": return "\\\\";;
  155. case '"': return '\"';;
  156. case "<": return "&lt;";
  157. case ">": return "&gt;";
  158. default: return s;
  159. }
  160. });
  161. },
  162. /*
  163. Merges all properties of object `b` into object `a`.
  164. `b.property` overwrites a.property`
  165. */
  166. merge: function(a, b) {
  167. var _new = {};
  168. for(var name in a) {
  169. if(a.hasOwnProperty(name)) {
  170. _new[name] = a[name];
  171. }
  172. };
  173. for(var name in b) {
  174. if(b.hasOwnProperty(name)) {
  175. _new[name] = b[name];
  176. }
  177. };
  178. return _new;
  179. },
  180. // by @langalex, support for arrays of strings
  181. create_context: function(_context) {
  182. if(this.is_object(_context)) {
  183. return _context;
  184. } else if(this.pragmas["JSTACHE-ENABLE-STRING-ARRAYS"]) {
  185. return {'.': _context};
  186. }
  187. },
  188. is_object: function(a) {
  189. return a && typeof a == 'object'
  190. },
  191. /*
  192. Thanks Doug Crockford
  193. JavaScript — The Good Parts lists an alternative that works better with
  194. frames. Frames can suck it, we use the simple version.
  195. */
  196. is_array: function(a) {
  197. return (a &&
  198. typeof a === 'object' &&
  199. a.constructor === Array);
  200. },
  201. /*
  202. Gets rid of leading and trailing whitespace
  203. */
  204. trim: function(s) {
  205. return s.replace(/^\s*|\s*$/g, '');
  206. },
  207. /*
  208. Why, why, why? Because IE. Cry, cry cry.
  209. */
  210. map: function(array, fn) {
  211. if (typeof array.map == "function") {
  212. return array.map(fn)
  213. } else {
  214. var r = [];
  215. var l = array.length;
  216. for(i=0;i<l;i++) {
  217. r.push(fn(array[i]));
  218. }
  219. return r;
  220. }
  221. }
  222. };
  223. return({
  224. name: "mustache.js",
  225. version: "0.2",
  226. /*
  227. Turns a template and view into HTML
  228. */
  229. to_html: function(template, view, partials) {
  230. return new Renderer().render(template, view, partials);
  231. }
  232. });
  233. }();