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

296 строки
7.8KB

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