memory.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. var path = require('path')
  2. var utils = require('../utils')
  3. /**
  4. * Loads templates from a provided object mapping.
  5. * @alias swig.loaders.memory
  6. * @example
  7. * var templates = {
  8. * "layout": "{% block content %}{% endblock %}",
  9. * "home.html": "{% extends 'layout.html' %}{% block content %}...{% endblock %}"
  10. * };
  11. * swig.setDefaults({ loader: swig.loaders.memory(templates) });
  12. *
  13. * @param {object} mapping Hash object with template paths as keys and template sources as values.
  14. * @param {string} [basepath] Path to the templates as string. Assigning this value allows you to use semi-absolute paths to templates instead of relative paths.
  15. */
  16. module.exports = function (mapping, basepath) {
  17. var ret = {}
  18. basepath = basepath ? path.resolve(basepath) : null
  19. /**
  20. * Resolves <var>to</var> to an absolute path or unique identifier. This is used for building correct, normalized, and absolute paths to a given template.
  21. * @alias resolve
  22. * @param {string} to Non-absolute identifier or pathname to a file.
  23. * @param {string} [from] If given, should attempt to find the <var>to</var> path in relation to this given, known path.
  24. * @return {string}
  25. */
  26. ret.resolve = function (to, from) {
  27. if (basepath) {
  28. from = basepath
  29. } else {
  30. from = from ? path.dirname(from) : '/'
  31. }
  32. return path.resolve(from, to)
  33. }
  34. /**
  35. * Loads a single template. Given a unique <var>identifier</var> found by the <var>resolve</var> method this should return the given template.
  36. * @alias load
  37. * @param {string} identifier Unique identifier of a template (possibly an absolute path).
  38. * @param {function} [cb] Asynchronous callback function. If not provided, this method should run synchronously.
  39. * @return {string} Template source string.
  40. */
  41. ret.load = function (pathname, cb) {
  42. var src, paths
  43. paths = [pathname, pathname.replace(/^(\/|\\)/, '')]
  44. src = mapping[paths[0]] || mapping[paths[1]]
  45. if (!src) {
  46. utils.throwError('Unable to find template "' + pathname + '".')
  47. }
  48. if (cb) {
  49. cb(null, src)
  50. return
  51. }
  52. return src
  53. }
  54. return ret
  55. }