index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. 'use strict';
  2. const ejs = require('ejs');
  3. const fs = require('fs');
  4. const path = require('path');
  5. const Block = require('./block');
  6. /**
  7. * Apply the given `view` as the layout for the current template,
  8. * using the current options/locals. The current template will be
  9. * supplied to the given `view` as `body`, along with any `blocks`
  10. * added by child templates.
  11. *
  12. * `options` are bound to `this` in renderFile, you just call
  13. * `layout('myview')`
  14. *
  15. * @param {String} view
  16. * @api private
  17. */
  18. function layout(view) {
  19. this._layoutFile = view;
  20. }
  21. /**
  22. * Return the block with the given name, create it if necessary.
  23. * Optionally append the given html to the block.
  24. *
  25. * The returned Block can append, prepend or replace the block,
  26. * as well as render it when included in a parent template.
  27. *
  28. * @param {String} name
  29. * @param {String} html
  30. * @return {Block}
  31. * @api private
  32. */
  33. function block(name, html) {
  34. // bound to the blocks object in renderFile
  35. var blk = this[name];
  36. if (!blk) {
  37. // always create, so if we request a
  38. // non-existent block we'll get a new one
  39. blk = this[name] = new Block();
  40. }
  41. if (html) {
  42. blk.append(html);
  43. }
  44. return blk;
  45. }
  46. /**
  47. * Express 3.x Layout & Partial support for EJS.
  48. *
  49. * The `partial` feature from Express 2.x is back as a template engine,
  50. * along with support for `layout` and `block/script/stylesheet`.
  51. *
  52. *
  53. * Example index.ejs:
  54. *
  55. * <% layout('boilerplate') %>
  56. * <h1>I am the <%=what%> template</h1>
  57. * <% script('foo.js') %>
  58. *
  59. *
  60. * Example boilerplate.ejs:
  61. *
  62. * <html>
  63. * <head>
  64. * <title>It's <%=who%></title>
  65. * <%-scripts%>
  66. * </head>
  67. * <body><%-body%></body>
  68. * </html>
  69. *
  70. *
  71. * Sample app:
  72. *
  73. * var express = require('express')
  74. * , app = express();
  75. *
  76. * // use ejs-locals for all ejs templates:
  77. * app.engine('ejs', require('ejs-locals'));
  78. *
  79. * // render 'index' into 'boilerplate':
  80. * app.get('/',function(req,res,next){
  81. * res.render('index', { what: 'best', who: 'me' });
  82. * });
  83. *
  84. * app.listen(3000);
  85. *
  86. * Example output for GET /:
  87. *
  88. * <html>
  89. * <head>
  90. * <title>It's me</title>
  91. * <script src="foo.js"></script>
  92. * </head>
  93. * <body><h1>I am the best template</h1></body>
  94. * </html>
  95. *
  96. */
  97. function compile(file, options, cb) {
  98. // Express used to set options.locals for us, but now we do it ourselves
  99. // (EJS does some __proto__ magic to expose these funcs/values in the template)
  100. if (!options.locals) {
  101. options.locals = {};
  102. }
  103. if (!options.locals.blocks) {
  104. // one set of blocks no matter how often we recurse
  105. var blocks = {};
  106. options.blocks = blocks;
  107. options.block = block.bind(blocks);
  108. }
  109. // override locals for layout/partial bound to current options
  110. options.locals.layout = layout.bind(options);
  111. options.locals.partial = partial.bind(options);
  112. try {
  113. var fn = ejs.compile(file, options);
  114. } catch (ex) {
  115. cb(ex);
  116. return;
  117. }
  118. cb(null, fn.toString());
  119. }
  120. // var renderFile = function (file, locals, options) {
  121. // return new Promise((resolve, reject) => {
  122. // ejs.renderFile(file, locals, options, (err, html) => {
  123. // if (err) {
  124. // return reject(err);
  125. // }
  126. // resolve(html);
  127. // });
  128. // });
  129. // };
  130. var render = function(file, locals, options, fn) {
  131. ejs.renderFile(file, locals, options, function(err, html) {
  132. if (err) {
  133. return fn(err, html);
  134. }
  135. var layout = options._layoutFile;
  136. // for backward-compatibility, allow options to
  137. // set a default layout file for the view or the app
  138. // (NB:- not called `layout` any more so it doesn't
  139. // conflict with the layout() function)
  140. if (layout === undefined) {
  141. layout = options._layoutFile;
  142. }
  143. if (layout) {
  144. // use default extension
  145. var engine = options.settings['view engine'] || 'ejs',
  146. desiredExt = '.' + engine;
  147. // apply default layout if only "true" was set
  148. if (layout === true) {
  149. layout = path.sep + 'layout' + desiredExt;
  150. }
  151. if (path.extname(layout) !== desiredExt) {
  152. layout += desiredExt;
  153. }
  154. // clear to make sure we don't recurse forever (layouts can be nested)
  155. delete options._layoutFile;
  156. // make sure caching works inside ejs.renderFile/render
  157. delete options.filename;
  158. if (layout.length > 0) {
  159. var views = options.settings.views;
  160. var l = layout;
  161. if (!Array.isArray(views)) {
  162. views = [views];
  163. }
  164. for (var i = 0; i < views.length; i++) {
  165. layout = path.join(views[i], l);
  166. // use the first found layout
  167. if (fs.existsSync(layout)) {
  168. break;
  169. }
  170. }
  171. }
  172. // now recurse and use the current result as `body` in the layout:
  173. options.body = html;
  174. renderFile(layout, options, fn);
  175. } else {
  176. // no layout, just do the default:
  177. fn(null, html);
  178. }
  179. });
  180. };
  181. function renderFile(file, options, fn) {
  182. // Express used to set options.locals for us, but now we do it ourselves
  183. // (EJS does some __proto__ magic to expose these funcs/values in the template)
  184. if (!options.locals) {
  185. options.locals = {};
  186. }
  187. if (!options.locals.blocks) {
  188. // one set of blocks no matter how often we recurse
  189. var blocks = {};
  190. options.locals.blocks = blocks;
  191. options.block = block.bind(blocks);
  192. }
  193. // override locals for layout/partial bound to current options
  194. options.layout = layout.bind(options);
  195. options.partial = partial.bind(options);
  196. options.filename = file;
  197. ejs.renderFile(file, options, function(err, html) {
  198. if (err) {
  199. return fn(err, html);
  200. }
  201. var layout = options.locals._layoutFile;
  202. // for backward-compatibility, allow options to
  203. // set a default layout file for the view or the app
  204. // (NB:- not called `layout` any more so it doesn't
  205. // conflict with the layout() function)
  206. if (layout === undefined) {
  207. layout = options._layoutFile;
  208. }
  209. if (layout) {
  210. // use default extension
  211. var engine = options.settings['view engine'] || 'ejs',
  212. desiredExt = '.' + engine;
  213. // apply default layout if only "true" was set
  214. if (layout === true) {
  215. layout = path.sep + 'layout' + desiredExt;
  216. }
  217. if (path.extname(layout) !== desiredExt) {
  218. layout += desiredExt;
  219. }
  220. // clear to make sure we don't recurse forever (layouts can be nested)
  221. delete options.locals._layoutFile;
  222. delete options._layoutFile;
  223. // make sure caching works inside ejs.renderFile/render
  224. options.filename;
  225. if (layout.length > 0) {
  226. var views = options.settings.views;
  227. var l = layout;
  228. if (!Array.isArray(views)) {
  229. views = [views];
  230. }
  231. for (var i = 0; i < views.length; i++) {
  232. layout = path.join(views[i], l);
  233. // use the first found layout
  234. if (fs.existsSync(layout)) {
  235. break;
  236. }
  237. }
  238. }
  239. // now recurse and use the current result as `body` in the layout:
  240. options.body = html;
  241. renderFile(layout, options, fn);
  242. } else {
  243. // no layout, just do the default:
  244. fn(null, html);
  245. }
  246. });
  247. }
  248. /**
  249. * Memory cache for resolved object names.
  250. */
  251. var cache = {};
  252. /**
  253. * Resolve partial object name from the view path.
  254. *
  255. * Examples:
  256. *
  257. * "user.ejs" becomes "user"
  258. * "forum thread.ejs" becomes "forumThread"
  259. * "forum/thread/post.ejs" becomes "post"
  260. * "blog-post.ejs" becomes "blogPost"
  261. *
  262. * @return {String}
  263. * @api private
  264. */
  265. function resolveObjectName(view) {
  266. return cache[view] || (cache[view] = view
  267. .split('/')
  268. .slice(-1)[0]
  269. .split('.')[0]
  270. .replace(/^_/, '')
  271. .replace(/[^a-zA-Z0-9 ]+/g, ' ')
  272. .split(/ +/).map(function(word, i) {
  273. return i ? word[0].toUpperCase() + word.substr(1) : word;
  274. }).join(''));
  275. }
  276. /**
  277. * Lookup partial path from base path of current template:
  278. *
  279. * - partial `_<name>`
  280. * - any `<name>/index`
  281. * - non-layout `../<name>/index`
  282. * - any `<root>/<name>`
  283. * - partial `<root>/_<name>`
  284. *
  285. * Options:
  286. *
  287. * - `cache` store the resolved path for the view, to avoid disk I/O
  288. *
  289. * @param {String} root, full base path of calling template
  290. * @param {String} partial, name of the partial to lookup (can be a relative path)
  291. * @param {Object} options, for `options.cache` behavior
  292. * @return {String}
  293. * @api private
  294. */
  295. function lookup(root, partial, options) {
  296. const engine = options.settings['view engine'] || 'ejs';
  297. const desiredExt = '.' + engine;
  298. const ext = path.extname(partial) || desiredExt;
  299. const key = [root, partial, ext].join('-');
  300. const partialPath = partial;
  301. if (options.cache && cache[key]) {
  302. return cache[key];
  303. }
  304. // Make sure we use dirname in case of relative partials
  305. // ex: for partial('../user') look for /path/to/root/../user.ejs
  306. var dir = path.dirname(partial);
  307. var base = path.basename(partial, ext);
  308. if (!options._isRelativeToViews) {
  309. var views = options.settings.views;
  310. options._isRelativeToViews = true;
  311. if (!Array.isArray(views)) {
  312. views = [views];
  313. }
  314. for (var i = 0; i < views.length; i++) {
  315. partial = lookup(views[i], partialPath, options);
  316. if (partial) {
  317. // reset state for when the partial has a partial lookup of its own
  318. options._isRelativeToViews = false;
  319. return partial;
  320. }
  321. }
  322. }
  323. // _ prefix takes precedence over the direct path
  324. // ex: for partial('user') look for /root/_user.ejs
  325. partial = path.resolve(root, dir, '_' + base + ext);
  326. if (fs.existsSync(partial)) {
  327. return options.cache ? cache[key] = partial : partial;
  328. }
  329. // Try the direct path
  330. // ex: for partial('user') look for /root/user.ejs
  331. partial = path.resolve(root, dir, base + ext);
  332. if (fs.existsSync(partial)) {
  333. return options.cache ? cache[key] = partial : partial;
  334. }
  335. // Try index
  336. // ex: for partial('user') look for /root/user/index.ejs
  337. partial = path.resolve(root, dir, base, 'index' + ext);
  338. if (fs.existsSync(partial)) {
  339. return options.cache ? cache[key] = partial : partial;
  340. }
  341. // Try relative to the app views
  342. // FIXME:
  343. // * there are other path types that Express 2.0 used to support but
  344. // the structure of the lookup involved View class methods that we
  345. // don't have access to any more
  346. // * we have no tests for finding partials that aren't relative to
  347. // the calling view
  348. return null;
  349. }
  350. /**
  351. * Render `view` partial with the given `options`. Optionally a
  352. * callback `fn(err, str)` may be passed instead of writing to
  353. * the socket.
  354. *
  355. * Options:
  356. *
  357. * - `object` Single object with name derived from the view (unless `as` is present)
  358. *
  359. * - `as` Variable name for each `collection` value, defaults to the view name.
  360. * * as: 'something' will add the `something` local variable
  361. * * as: this will use the collection value as the template context
  362. * * as: global will merge the collection value's properties with `locals`
  363. *
  364. * - `collection` Array of objects, the name is derived from the view name itself.
  365. * For example _video.html_ will have a object _video_ available to it.
  366. *
  367. * @param {String} view
  368. * @param {Object|Array} options, collection or object
  369. * @return {String}
  370. * @api private
  371. */
  372. function partial(view) {
  373. var collection;
  374. var object;
  375. // find view, relative to this filename
  376. // (FIXME: filename is set by ejs engine, other engines may need more help)
  377. var root = path.dirname(this.filename);
  378. var file = lookup(root, view, this);
  379. var key = file + ':string';
  380. if (!file) {
  381. throw new Error(`Could not find partial '${view}'`);
  382. }
  383. // read view
  384. var source = this.cache ? cache[key] || (cache[key] = fs.readFileSync(file, 'utf8')) : fs.readFileSync(file, 'utf8');
  385. return ejs.render(source, this);
  386. }
  387. renderFile.compile = compile;
  388. renderFile.partial = partial;
  389. renderFile.block = block;
  390. renderFile.layout = layout;
  391. module.exports = renderFile;