ejs.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /*!
  2. * EJS
  3. * Copyright(c) 2012 TJ Holowaychuk <tj@vision-media.ca>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module dependencies.
  8. */
  9. var utils = require('./utils')
  10. , path = require('path')
  11. , dirname = path.dirname
  12. , extname = path.extname
  13. , join = path.join
  14. , fs = require('fs')
  15. , read = fs.readFileSync;
  16. /**
  17. * Filters.
  18. *
  19. * @type Object
  20. */
  21. var filters = exports.filters = require('./filters');
  22. /**
  23. * Intermediate js cache.
  24. *
  25. * @type Object
  26. */
  27. var cache = {};
  28. /**
  29. * Clear intermediate js cache.
  30. *
  31. * @api public
  32. */
  33. exports.clearCache = function(){
  34. cache = {};
  35. };
  36. /**
  37. * Translate filtered code into function calls.
  38. *
  39. * @param {String} js
  40. * @return {String}
  41. * @api private
  42. */
  43. function filtered(js) {
  44. return js.substr(1).split('|').reduce(function(js, filter){
  45. var parts = filter.split(':')
  46. , name = parts.shift()
  47. , args = parts.join(':') || '';
  48. if (args) args = ', ' + args;
  49. return 'filters.' + name + '(' + js + args + ')';
  50. });
  51. };
  52. /**
  53. * Re-throw the given `err` in context to the
  54. * `str` of ejs, `filename`, and `lineno`.
  55. *
  56. * @param {Error} err
  57. * @param {String} str
  58. * @param {String} filename
  59. * @param {String} lineno
  60. * @api private
  61. */
  62. function rethrow(err, str, filename, lineno){
  63. var lines = str.split('\n')
  64. , start = Math.max(lineno - 3, 0)
  65. , end = Math.min(lines.length, lineno + 3);
  66. // Error context
  67. var context = lines.slice(start, end).map(function(line, i){
  68. var curr = i + start + 1;
  69. return (curr == lineno ? ' >> ' : ' ')
  70. + curr
  71. + '| '
  72. + line;
  73. }).join('\n');
  74. // Alter exception message
  75. err.path = filename;
  76. err.message = (filename || 'ejs') + ':'
  77. + lineno + '\n'
  78. + context + '\n\n'
  79. + err.message;
  80. throw err;
  81. }
  82. /**
  83. * Parse the given `str` of ejs, returning the function body.
  84. *
  85. * @param {String} str
  86. * @return {String}
  87. * @api public
  88. */
  89. var parse = exports.parse = function(str, options){
  90. var options = options || {}
  91. , open = options.open || exports.open || '<%'
  92. , close = options.close || exports.close || '%>'
  93. , filename = options.filename
  94. , compileDebug = options.compileDebug !== false
  95. , buf = "";
  96. buf += 'var buf = [];';
  97. if (false !== options._with) buf += '\nwith (locals || {}) { (function(){ ';
  98. buf += '\n buf.push(\'';
  99. var lineno = 1;
  100. var consumeEOL = false;
  101. for (var i = 0, len = str.length; i < len; ++i) {
  102. var stri = str[i];
  103. if (str.slice(i, open.length + i) == open) {
  104. i += open.length
  105. var prefix, postfix, line = (compileDebug ? '__stack.lineno=' : '') + lineno;
  106. switch (str[i]) {
  107. case '=':
  108. prefix = "', escape((" + line + ', ';
  109. postfix = ")), '";
  110. ++i;
  111. break;
  112. case '-':
  113. prefix = "', (" + line + ', ';
  114. postfix = "), '";
  115. ++i;
  116. break;
  117. default:
  118. prefix = "');" + line + ';';
  119. postfix = "; buf.push('";
  120. }
  121. var end = str.indexOf(close, i);
  122. if (end < 0){
  123. throw new Error('Could not find matching close tag "' + close + '".');
  124. }
  125. var js = str.substring(i, end)
  126. , start = i
  127. , include = null
  128. , n = 0;
  129. if ('-' == js[js.length-1]){
  130. js = js.substring(0, js.length - 2);
  131. consumeEOL = true;
  132. }
  133. if (0 == js.trim().indexOf('include')) {
  134. var name = js.trim().slice(7).trim();
  135. if (!filename) throw new Error('filename option is required for includes');
  136. var path = resolveInclude(name, filename);
  137. include = read(path, 'utf8');
  138. include = exports.parse(include, { filename: path, _with: false, open: open, close: close, compileDebug: compileDebug });
  139. buf += "' + (function(){" + include + "})() + '";
  140. js = '';
  141. }
  142. while (~(n = js.indexOf("\n", n))) n++, lineno++;
  143. if (js.substr(0, 1) == ':') js = filtered(js);
  144. if (js) {
  145. if (js.lastIndexOf('//') > js.lastIndexOf('\n')) js += '\n';
  146. buf += prefix;
  147. buf += js;
  148. buf += postfix;
  149. }
  150. i += end - start + close.length - 1;
  151. } else if (stri == "\\") {
  152. buf += "\\\\";
  153. } else if (stri == "'") {
  154. buf += "\\'";
  155. } else if (stri == "\r") {
  156. // ignore
  157. } else if (stri == "\n") {
  158. if (consumeEOL) {
  159. consumeEOL = false;
  160. } else {
  161. buf += "\\n";
  162. lineno++;
  163. }
  164. } else {
  165. buf += stri;
  166. }
  167. }
  168. if (false !== options._with) buf += "'); })();\n} \nreturn buf.join('');";
  169. else buf += "');\nreturn buf.join('');";
  170. return buf;
  171. };
  172. /**
  173. * Compile the given `str` of ejs into a `Function`.
  174. *
  175. * @param {String} str
  176. * @param {Object} options
  177. * @return {Function}
  178. * @api public
  179. */
  180. var compile = exports.compile = function(str, options){
  181. options = options || {};
  182. var escape = options.escape || utils.escape;
  183. var input = JSON.stringify(str)
  184. , compileDebug = options.compileDebug !== false
  185. , client = options.client
  186. , filename = options.filename
  187. ? JSON.stringify(options.filename)
  188. : 'undefined';
  189. if (compileDebug) {
  190. // Adds the fancy stack trace meta info
  191. str = [
  192. 'var __stack = { lineno: 1, input: ' + input + ', filename: ' + filename + ' };',
  193. rethrow.toString(),
  194. 'try {',
  195. exports.parse(str, options),
  196. '} catch (err) {',
  197. ' rethrow(err, __stack.input, __stack.filename, __stack.lineno);',
  198. '}'
  199. ].join("\n");
  200. } else {
  201. str = exports.parse(str, options);
  202. }
  203. if (options.debug) console.log(str);
  204. if (client) str = 'escape = escape || ' + escape.toString() + ';\n' + str;
  205. try {
  206. var fn = new Function('locals, filters, escape, rethrow', str);
  207. } catch (err) {
  208. if ('SyntaxError' == err.name) {
  209. err.message += options.filename
  210. ? ' in ' + filename
  211. : ' while compiling ejs';
  212. }
  213. throw err;
  214. }
  215. if (client) return fn;
  216. return function(locals){
  217. return fn.call(this, locals, filters, escape, rethrow);
  218. }
  219. };
  220. /**
  221. * Render the given `str` of ejs.
  222. *
  223. * Options:
  224. *
  225. * - `locals` Local variables object
  226. * - `cache` Compiled functions are cached, requires `filename`
  227. * - `filename` Used by `cache` to key caches
  228. * - `scope` Function execution context
  229. * - `debug` Output generated function body
  230. * - `open` Open tag, defaulting to "<%"
  231. * - `close` Closing tag, defaulting to "%>"
  232. *
  233. * @param {String} str
  234. * @param {Object} options
  235. * @return {String}
  236. * @api public
  237. */
  238. exports.render = function(str, options){
  239. var fn
  240. , options = options || {};
  241. if (options.cache) {
  242. if (options.filename) {
  243. fn = cache[options.filename] || (cache[options.filename] = compile(str, options));
  244. } else {
  245. throw new Error('"cache" option requires "filename".');
  246. }
  247. } else {
  248. fn = compile(str, options);
  249. }
  250. options.__proto__ = options.locals;
  251. return fn.call(options.scope, options);
  252. };
  253. /**
  254. * Render an EJS file at the given `path` and callback `fn(err, str)`.
  255. *
  256. * @param {String} path
  257. * @param {Object|Function} options or callback
  258. * @param {Function} fn
  259. * @api public
  260. */
  261. exports.renderFile = function(path, options, fn){
  262. var key = path + ':string';
  263. if ('function' == typeof options) {
  264. fn = options, options = {};
  265. }
  266. options.filename = path;
  267. var str;
  268. try {
  269. str = options.cache
  270. ? cache[key] || (cache[key] = read(path, 'utf8'))
  271. : read(path, 'utf8');
  272. } catch (err) {
  273. fn(err);
  274. return;
  275. }
  276. fn(null, exports.render(str, options));
  277. };
  278. /**
  279. * Resolve include `name` relative to `filename`.
  280. *
  281. * @param {String} name
  282. * @param {String} filename
  283. * @return {String}
  284. * @api private
  285. */
  286. function resolveInclude(name, filename) {
  287. var path = join(dirname(filename), name);
  288. var ext = extname(name);
  289. if (!ext) path += '.ejs';
  290. return path;
  291. }
  292. // express support
  293. exports.__express = exports.renderFile;
  294. /**
  295. * Expose to require().
  296. */
  297. if (require.extensions) {
  298. require.extensions['.ejs'] = function (module, filename) {
  299. filename = filename || module.filename;
  300. var options = { filename: filename, client: true }
  301. , template = fs.readFileSync(filename).toString()
  302. , fn = compile(template, options);
  303. module._compile('module.exports = ' + fn.toString() + ';', filename);
  304. };
  305. } else if (require.registerExtension) {
  306. require.registerExtension('.ejs', function(src) {
  307. return compile(src, {});
  308. });
  309. }