partial.js 1.1 KB

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