hogan.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /*
  2. * Copyright 2011 Twitter, Inc.
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. var Hogan = {};
  16. (function (Hogan, useArrayBuffer) {
  17. Hogan.Template = function (renderFunc, text, compiler, options) {
  18. this.r = renderFunc || this.r;
  19. this.c = compiler;
  20. this.options = options;
  21. this.text = text || '';
  22. this.buf = (useArrayBuffer) ? [] : '';
  23. }
  24. Hogan.Template.prototype = {
  25. // render: replaced by generated code.
  26. r: function (context, partials, indent) { return ''; },
  27. // variable escaping
  28. v: hoganEscape,
  29. // triple stache
  30. t: coerceToString,
  31. render: function render(context, partials, indent) {
  32. return this.ri([context], partials || {}, indent);
  33. },
  34. // render internal -- a hook for overrides that catches partials too
  35. ri: function (context, partials, indent) {
  36. return this.r(context, partials, indent);
  37. },
  38. // tries to find a partial in the curent scope and render it
  39. rp: function(name, context, partials, indent) {
  40. var partial = partials[name];
  41. if (!partial) {
  42. return '';
  43. }
  44. if (this.c && typeof partial == 'string') {
  45. partial = this.c.compile(partial, this.options);
  46. }
  47. return partial.ri(context, partials, indent);
  48. },
  49. // render a section
  50. rs: function(context, partials, section) {
  51. var tail = context[context.length - 1];
  52. if (!isArray(tail)) {
  53. section(context, partials, this);
  54. return;
  55. }
  56. for (var i = 0; i < tail.length; i++) {
  57. context.push(tail[i]);
  58. section(context, partials, this);
  59. context.pop();
  60. }
  61. },
  62. // maybe start a section
  63. s: function(val, ctx, partials, inverted, start, end, tags) {
  64. var pass;
  65. if (isArray(val) && val.length === 0) {
  66. return false;
  67. }
  68. if (typeof val == 'function') {
  69. val = this.ls(val, ctx, partials, inverted, start, end, tags);
  70. }
  71. pass = (val === '') || !!val;
  72. if (!inverted && pass && ctx) {
  73. ctx.push((typeof val == 'object') ? val : ctx[ctx.length - 1]);
  74. }
  75. return pass;
  76. },
  77. // find values with dotted names
  78. d: function(key, ctx, partials, returnFound) {
  79. var names = key.split('.'),
  80. val = this.f(names[0], ctx, partials, returnFound),
  81. cx = null;
  82. if (key === '.' && isArray(ctx[ctx.length - 2])) {
  83. return ctx[ctx.length - 1];
  84. }
  85. for (var i = 1; i < names.length; i++) {
  86. if (val && typeof val == 'object' && names[i] in val) {
  87. cx = val;
  88. val = val[names[i]];
  89. } else {
  90. val = '';
  91. }
  92. }
  93. if (returnFound && !val) {
  94. return false;
  95. }
  96. if (!returnFound && typeof val == 'function') {
  97. ctx.push(cx);
  98. val = this.lv(val, ctx, partials);
  99. ctx.pop();
  100. }
  101. return val;
  102. },
  103. // find values with normal names
  104. f: function(key, ctx, partials, returnFound) {
  105. var val = false,
  106. v = null,
  107. found = false;
  108. for (var i = ctx.length - 1; i >= 0; i--) {
  109. v = ctx[i];
  110. if (v && typeof v == 'object' && key in v) {
  111. val = v[key];
  112. found = true;
  113. break;
  114. }
  115. }
  116. if (!found) {
  117. return (returnFound) ? false : "";
  118. }
  119. if (!returnFound && typeof val == 'function') {
  120. val = this.lv(val, ctx, partials);
  121. }
  122. return val;
  123. },
  124. // higher order templates
  125. ho: function(val, cx, partials, text, tags) {
  126. var compiler = this.c;
  127. var options = this.options;
  128. options.delimiters = tags;
  129. var text = val.call(cx, text);
  130. text = (text == null) ? String(text) : text.toString();
  131. this.b(compiler.compile(text, options).render(cx, partials));
  132. return false;
  133. },
  134. // template result buffering
  135. b: (useArrayBuffer) ? function(s) { this.buf.push(s); } :
  136. function(s) { this.buf += s; },
  137. fl: (useArrayBuffer) ? function() { var r = this.buf.join(''); this.buf = []; return r; } :
  138. function() { var r = this.buf; this.buf = ''; return r; },
  139. // lambda replace section
  140. ls: function(val, ctx, partials, inverted, start, end, tags) {
  141. var cx = ctx[ctx.length - 1],
  142. t = null;
  143. if (!inverted && this.c && val.length > 0) {
  144. return this.ho(val, cx, partials, this.text.substring(start, end), tags);
  145. }
  146. t = val.call(cx);
  147. if (typeof t == 'function') {
  148. if (inverted) {
  149. return true;
  150. } else if (this.c) {
  151. return this.ho(t, cx, partials, this.text.substring(start, end), tags);
  152. }
  153. }
  154. return t;
  155. },
  156. // lambda replace variable
  157. lv: function(val, ctx, partials) {
  158. var cx = ctx[ctx.length - 1];
  159. var result = val.call(cx);
  160. if (typeof result == 'function') {
  161. result = coerceToString(result.call(cx));
  162. if (this.c && ~result.indexOf("{\u007B")) {
  163. return this.c.compile(result, this.options).render(cx, partials);
  164. }
  165. }
  166. return coerceToString(result);
  167. }
  168. };
  169. var rAmp = /&/g,
  170. rLt = /</g,
  171. rGt = />/g,
  172. rApos =/\'/g,
  173. rQuot = /\"/g,
  174. hChars =/[&<>\"\']/;
  175. function coerceToString(val) {
  176. return String((val === null || val === undefined) ? '' : val);
  177. }
  178. function hoganEscape(str) {
  179. str = coerceToString(str);
  180. return hChars.test(str) ?
  181. str
  182. .replace(rAmp,'&amp;')
  183. .replace(rLt,'&lt;')
  184. .replace(rGt,'&gt;')
  185. .replace(rApos,'&#39;')
  186. .replace(rQuot, '&quot;') :
  187. str;
  188. }
  189. var isArray = Array.isArray || function(a) {
  190. return Object.prototype.toString.call(a) === '[object Array]';
  191. };
  192. })(typeof exports !== 'undefined' ? exports : Hogan);
  193. (function (Hogan) {
  194. // Setup regex assignments
  195. // remove whitespace according to Mustache spec
  196. var rIsWhitespace = /\S/,
  197. rQuot = /\"/g,
  198. rNewline = /\n/g,
  199. rCr = /\r/g,
  200. rSlash = /\\/g,
  201. tagTypes = {
  202. '#': 1, '^': 2, '/': 3, '!': 4, '>': 5,
  203. '<': 6, '=': 7, '_v': 8, '{': 9, '&': 10
  204. };
  205. Hogan.scan = function scan(text, delimiters) {
  206. var len = text.length,
  207. IN_TEXT = 0,
  208. IN_TAG_TYPE = 1,
  209. IN_TAG = 2,
  210. state = IN_TEXT,
  211. tagType = null,
  212. tag = null,
  213. buf = '',
  214. tokens = [],
  215. seenTag = false,
  216. i = 0,
  217. lineStart = 0,
  218. otag = '{{',
  219. ctag = '}}';
  220. function addBuf() {
  221. if (buf.length > 0) {
  222. tokens.push(new String(buf));
  223. buf = '';
  224. }
  225. }
  226. function lineIsWhitespace() {
  227. var isAllWhitespace = true;
  228. for (var j = lineStart; j < tokens.length; j++) {
  229. isAllWhitespace =
  230. (tokens[j].tag && tagTypes[tokens[j].tag] < tagTypes['_v']) ||
  231. (!tokens[j].tag && tokens[j].match(rIsWhitespace) === null);
  232. if (!isAllWhitespace) {
  233. return false;
  234. }
  235. }
  236. return isAllWhitespace;
  237. }
  238. function filterLine(haveSeenTag, noNewLine) {
  239. addBuf();
  240. if (haveSeenTag && lineIsWhitespace()) {
  241. for (var j = lineStart, next; j < tokens.length; j++) {
  242. if (!tokens[j].tag) {
  243. if ((next = tokens[j+1]) && next.tag == '>') {
  244. // set indent to token value
  245. next.indent = tokens[j].toString()
  246. }
  247. tokens.splice(j, 1);
  248. }
  249. }
  250. } else if (!noNewLine) {
  251. tokens.push({tag:'\n'});
  252. }
  253. seenTag = false;
  254. lineStart = tokens.length;
  255. }
  256. function changeDelimiters(text, index) {
  257. var close = '=' + ctag,
  258. closeIndex = text.indexOf(close, index),
  259. delimiters = trim(
  260. text.substring(text.indexOf('=', index) + 1, closeIndex)
  261. ).split(' ');
  262. otag = delimiters[0];
  263. ctag = delimiters[1];
  264. return closeIndex + close.length - 1;
  265. }
  266. if (delimiters) {
  267. delimiters = delimiters.split(' ');
  268. otag = delimiters[0];
  269. ctag = delimiters[1];
  270. }
  271. for (i = 0; i < len; i++) {
  272. if (state == IN_TEXT) {
  273. if (tagChange(otag, text, i)) {
  274. --i;
  275. addBuf();
  276. state = IN_TAG_TYPE;
  277. } else {
  278. if (text.charAt(i) == '\n') {
  279. filterLine(seenTag);
  280. } else {
  281. buf += text.charAt(i);
  282. }
  283. }
  284. } else if (state == IN_TAG_TYPE) {
  285. i += otag.length - 1;
  286. tag = tagTypes[text.charAt(i + 1)];
  287. tagType = tag ? text.charAt(i + 1) : '_v';
  288. if (tagType == '=') {
  289. i = changeDelimiters(text, i);
  290. state = IN_TEXT;
  291. } else {
  292. if (tag) {
  293. i++;
  294. }
  295. state = IN_TAG;
  296. }
  297. seenTag = i;
  298. } else {
  299. if (tagChange(ctag, text, i)) {
  300. tokens.push({tag: tagType, n: trim(buf), otag: otag, ctag: ctag,
  301. i: (tagType == '/') ? seenTag - ctag.length : i + otag.length});
  302. buf = '';
  303. i += ctag.length - 1;
  304. state = IN_TEXT;
  305. if (tagType == '{') {
  306. if (ctag == '}}') {
  307. i++;
  308. } else {
  309. cleanTripleStache(tokens[tokens.length - 1]);
  310. }
  311. }
  312. } else {
  313. buf += text.charAt(i);
  314. }
  315. }
  316. }
  317. filterLine(seenTag, true);
  318. return tokens;
  319. }
  320. function cleanTripleStache(token) {
  321. if (token.n.substr(token.n.length - 1) === '}') {
  322. token.n = token.n.substring(0, token.n.length - 1);
  323. }
  324. }
  325. function trim(s) {
  326. if (s.trim) {
  327. return s.trim();
  328. }
  329. return s.replace(/^\s*|\s*$/g, '');
  330. }
  331. function tagChange(tag, text, index) {
  332. if (text.charAt(index) != tag.charAt(0)) {
  333. return false;
  334. }
  335. for (var i = 1, l = tag.length; i < l; i++) {
  336. if (text.charAt(index + i) != tag.charAt(i)) {
  337. return false;
  338. }
  339. }
  340. return true;
  341. }
  342. function buildTree(tokens, kind, stack, customTags) {
  343. var instructions = [],
  344. opener = null,
  345. token = null;
  346. while (tokens.length > 0) {
  347. token = tokens.shift();
  348. if (token.tag == '#' || token.tag == '^' || isOpener(token, customTags)) {
  349. stack.push(token);
  350. token.nodes = buildTree(tokens, token.tag, stack, customTags);
  351. instructions.push(token);
  352. } else if (token.tag == '/') {
  353. if (stack.length === 0) {
  354. throw new Error('Closing tag without opener: /' + token.n);
  355. }
  356. opener = stack.pop();
  357. if (token.n != opener.n && !isCloser(token.n, opener.n, customTags)) {
  358. throw new Error('Nesting error: ' + opener.n + ' vs. ' + token.n);
  359. }
  360. opener.end = token.i;
  361. return instructions;
  362. } else {
  363. instructions.push(token);
  364. }
  365. }
  366. if (stack.length > 0) {
  367. throw new Error('missing closing tag: ' + stack.pop().n);
  368. }
  369. return instructions;
  370. }
  371. function isOpener(token, tags) {
  372. for (var i = 0, l = tags.length; i < l; i++) {
  373. if (tags[i].o == token.n) {
  374. token.tag = '#';
  375. return true;
  376. }
  377. }
  378. }
  379. function isCloser(close, open, tags) {
  380. for (var i = 0, l = tags.length; i < l; i++) {
  381. if (tags[i].c == close && tags[i].o == open) {
  382. return true;
  383. }
  384. }
  385. }
  386. Hogan.generate = function (tree, text, options) {
  387. var code = 'var _=this;_.b(i=i||"");' + walk(tree) + 'return _.fl();';
  388. if (options.asString) {
  389. return 'function(c,p,i){' + code + ';}';
  390. }
  391. return new Hogan.Template(new Function('c', 'p', 'i', code), text, Hogan, options);
  392. }
  393. function esc(s) {
  394. return s.replace(rSlash, '\\\\')
  395. .replace(rQuot, '\\\"')
  396. .replace(rNewline, '\\n')
  397. .replace(rCr, '\\r');
  398. }
  399. function chooseMethod(s) {
  400. return (~s.indexOf('.')) ? 'd' : 'f';
  401. }
  402. function walk(tree) {
  403. var code = '';
  404. for (var i = 0, l = tree.length; i < l; i++) {
  405. var tag = tree[i].tag;
  406. if (tag == '#') {
  407. code += section(tree[i].nodes, tree[i].n, chooseMethod(tree[i].n),
  408. tree[i].i, tree[i].end, tree[i].otag + " " + tree[i].ctag);
  409. } else if (tag == '^') {
  410. code += invertedSection(tree[i].nodes, tree[i].n,
  411. chooseMethod(tree[i].n));
  412. } else if (tag == '<' || tag == '>') {
  413. code += partial(tree[i]);
  414. } else if (tag == '{' || tag == '&') {
  415. code += tripleStache(tree[i].n, chooseMethod(tree[i].n));
  416. } else if (tag == '\n') {
  417. code += text('"\\n"' + (tree.length-1 == i ? '' : ' + i'));
  418. } else if (tag == '_v') {
  419. code += variable(tree[i].n, chooseMethod(tree[i].n));
  420. } else if (tag === undefined) {
  421. code += text('"' + esc(tree[i]) + '"');
  422. }
  423. }
  424. return code;
  425. }
  426. function section(nodes, id, method, start, end, tags) {
  427. return 'if(_.s(_.' + method + '("' + esc(id) + '",c,p,1),' +
  428. 'c,p,0,' + start + ',' + end + ',"' + tags + '")){' +
  429. '_.rs(c,p,' +
  430. 'function(c,p,_){' +
  431. walk(nodes) +
  432. '});c.pop();}';
  433. }
  434. function invertedSection(nodes, id, method) {
  435. return 'if(!_.s(_.' + method + '("' + esc(id) + '",c,p,1),c,p,1,0,0,"")){' +
  436. walk(nodes) +
  437. '};';
  438. }
  439. function partial(tok) {
  440. return '_.b(_.rp("' + esc(tok.n) + '",c,p,"' + (tok.indent || '') + '"));';
  441. }
  442. function tripleStache(id, method) {
  443. return '_.b(_.t(_.' + method + '("' + esc(id) + '",c,p,0)));';
  444. }
  445. function variable(id, method) {
  446. return '_.b(_.v(_.' + method + '("' + esc(id) + '",c,p,0)));';
  447. }
  448. function text(id) {
  449. return '_.b(' + id + ');';
  450. }
  451. Hogan.parse = function(tokens, text, options) {
  452. options = options || {};
  453. return buildTree(tokens, '', [], options.sectionTags || []);
  454. },
  455. Hogan.cache = {};
  456. Hogan.compile = function(text, options) {
  457. // options
  458. //
  459. // asString: false (default)
  460. //
  461. // sectionTags: [{o: '_foo', c: 'foo'}]
  462. // An array of object with o and c fields that indicate names for custom
  463. // section tags. The example above allows parsing of {{_foo}}{{/foo}}.
  464. //
  465. // delimiters: A string that overrides the default delimiters.
  466. // Example: "<% %>"
  467. //
  468. options = options || {};
  469. var key = text + '||' + !!options.asString;
  470. var t = this.cache[key];
  471. if (t) {
  472. return t;
  473. }
  474. t = this.generate(this.parse(this.scan(text, options.delimiters), text, options), text, options);
  475. return this.cache[key] = t;
  476. };
  477. })(typeof exports !== 'undefined' ? exports : Hogan);