base_controller.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. /**
  3. * 控制器基类
  4. *
  5. * @author CaiAoLin
  6. * @date 2017/10/11
  7. * @version
  8. */
  9. const moment = require('moment');
  10. const Controller = require('egg').Controller;
  11. const menuList = require('../../config/menu');
  12. class BaseController extends Controller {
  13. /**
  14. * 构造函数
  15. *
  16. * @param {Object} ctx - egg全局context
  17. * @return {void}
  18. */
  19. constructor(ctx) {
  20. super(ctx);
  21. ctx.menuList = menuList;
  22. ctx.menu = menuList[ctx.controllerName] ? menuList[ctx.controllerName] : {};
  23. ctx.title = ctx.menu.name ? ctx.menu.name : '';
  24. }
  25. /**
  26. * 渲染layout
  27. *
  28. * @param {String} view - 渲染的view
  29. * @param {Object} data - 渲染的数据
  30. * @param {String} modal - 渲染的modal
  31. * @return {void}
  32. */
  33. async layout(view, data = {}, modal = '') {
  34. // 获取消息提示
  35. let message = this.ctx.session.message;
  36. // 取出后删除
  37. this.ctx.session.message = null;
  38. data.moment = moment;
  39. try {
  40. data.min = this.app.config.min ? '.min' : '';
  41. const contentString = await this.ctx.renderView(view, data);
  42. const modalString = modal === '' ? '' : await this.ctx.renderView(modal, data);
  43. const renderData = {
  44. min: this.app.config.min ? '.min' : '',
  45. content: contentString,
  46. modal: modalString,
  47. message,
  48. };
  49. await this.ctx.render('layout/layout.ejs', renderData);
  50. } catch (err) {
  51. console.log(err);
  52. }
  53. }
  54. /**
  55. * 设置提示
  56. *
  57. * @param {String} message - 提示信息
  58. * @param {String} type - 提示类型
  59. * @return {void}
  60. */
  61. setMessage(type, message) {
  62. this.ctx.session.message = {
  63. type,
  64. message,
  65. };
  66. }
  67. }
  68. module.exports = BaseController;