index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict';
  2. const pathFn = require('path');
  3. const util = require('util');
  4. const Box = require('../box');
  5. const View = require('./view');
  6. const I18n = require('hexo-i18n');
  7. const _ = require('lodash');
  8. function Theme(ctx) {
  9. Box.call(this, ctx, ctx.theme_dir);
  10. this.config = {};
  11. this.views = {};
  12. this.processors = [
  13. require('./processors/config'),
  14. require('./processors/i18n'),
  15. require('./processors/source'),
  16. require('./processors/view')
  17. ];
  18. let languages = ctx.config.language;
  19. if (!Array.isArray(languages)) {
  20. languages = [languages];
  21. }
  22. languages.push('default');
  23. this.i18n = new I18n({
  24. languages: _(languages).compact().uniq().value()
  25. });
  26. const _View = this.View = function(path, data) {
  27. View.call(this, path, data);
  28. };
  29. util.inherits(_View, View);
  30. _View.prototype._theme = this;
  31. _View.prototype._render = ctx.render;
  32. _View.prototype._helper = ctx.extend.helper;
  33. }
  34. util.inherits(Theme, Box);
  35. Theme.prototype.getView = function(path) {
  36. // Replace backslashes on Windows
  37. path = path.replace(/\\/g, '/');
  38. const extname = pathFn.extname(path);
  39. const name = path.substring(0, path.length - extname.length);
  40. const views = this.views[name];
  41. if (!views) return;
  42. if (extname) {
  43. return views[extname];
  44. }
  45. return views[Object.keys(views)[0]];
  46. };
  47. Theme.prototype.setView = function(path, data) {
  48. const extname = pathFn.extname(path);
  49. const name = path.substring(0, path.length - extname.length);
  50. const views = this.views[name] = this.views[name] || {};
  51. views[extname] = new this.View(path, data);
  52. };
  53. Theme.prototype.removeView = function(path) {
  54. const extname = pathFn.extname(path);
  55. const name = path.substring(0, path.length - extname.length);
  56. const views = this.views[name];
  57. if (!views) return;
  58. delete views[extname];
  59. };
  60. module.exports = Theme;