partial.js 976 B

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. const { dirname, join } = require('path');
  3. module.exports = ctx => function partial(name, locals, options = {}) {
  4. if (typeof name !== 'string') throw new TypeError('name must be a string!');
  5. const { cache } = options;
  6. const viewDir = this.view_dir;
  7. const currentView = this.filename.substring(viewDir.length);
  8. const path = join(dirname(currentView), name);
  9. const view = ctx.theme.getView(path) || ctx.theme.getView(name);
  10. const viewLocals = { layout: false };
  11. if (!view) {
  12. throw new Error(`Partial ${name} does not exist. (in ${currentView})`);
  13. }
  14. if (options.only) {
  15. Object.assign(viewLocals, locals);
  16. } else {
  17. Object.assign(viewLocals, this, locals);
  18. }
  19. // Partial don't need layout
  20. viewLocals.layout = false;
  21. if (cache) {
  22. const cacheId = typeof cache === 'string' ? cache : view.path;
  23. return this.fragment_cache(cacheId, () => view.renderSync(viewLocals));
  24. }
  25. return view.renderSync(viewLocals);
  26. };