_node.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. var fs = require('fs');
  2. var path = require('path');
  3. module.exports = function (template) {
  4. var cacheStore = template.cache;
  5. var defaults = template.defaults;
  6. var rExtname;
  7. // 提供新的配置字段
  8. defaults.base = '';
  9. defaults.extname = '.html';
  10. defaults.encoding = 'utf-8';
  11. function compileFromFS(filename) {
  12. // 加载模板并编译
  13. var source = readTemplate(filename);
  14. if (typeof source === 'string') {
  15. return template.compile(source, {
  16. filename: filename
  17. });
  18. }
  19. }
  20. // 重写引擎编译结果获取方法
  21. template.get = function (filename) {
  22. var fn;
  23. if (cacheStore.hasOwnProperty(filename)) {
  24. // 使用内存缓存
  25. fn = cacheStore[filename];
  26. } else {
  27. fn = compileFromFS(filename);
  28. }
  29. return fn;
  30. };
  31. function readTemplate (id) {
  32. id = path.join(defaults.base, id + defaults.extname);
  33. if (id.indexOf(defaults.base) !== 0) {
  34. // 安全限制:禁止超出模板目录之外调用文件
  35. throw new Error('"' + id + '" is not in the template directory');
  36. } else {
  37. try {
  38. return fs.readFileSync(id, defaults.encoding);
  39. } catch (e) {}
  40. }
  41. }
  42. // 重写模板`include``语句实现方法,转换模板为绝对路径
  43. template.utils.$include = function (filename, data, from) {
  44. from = path.dirname(from);
  45. filename = path.join(from, filename);
  46. return template.renderFile(filename, data);
  47. }
  48. // express support
  49. template.__express = function (file, options, fn) {
  50. if (typeof options === 'function') {
  51. fn = options;
  52. options = {};
  53. }
  54. if (!rExtname) {
  55. // 去掉 express 传入的路径
  56. rExtname = new RegExp((defaults.extname + '$').replace(/\./g, '\\.'));
  57. }
  58. file = file.replace(rExtname, '');
  59. options.filename = file;
  60. fn(null, template.renderFile(file, options));
  61. };
  62. return template;
  63. }