UNPKG

mm_os

Version:

MM_OS服务端架构,用于快速构建应用程序,支持网站建设、小程序后台、AI应用、物联网(IOT/AIOT)、游戏服务端等多种场景。

91 lines (84 loc) 2.02 kB
const { Drive } = require('mm_machine'); const Tpl = require('mm_tpl'); /** * 渲染视图基类 * 渲染html或消息模板 */ class View extends Drive { static config = { // 视图名称 name: 'default', // 视图目录 dir: './static/template', }; /** * 构造函数 * @param {object} config 配置参数 * @param {object} parent 父对象 */ constructor(config, parent) { super({ ...View.config, ...config || {} }, parent); } } /** * 预设 */ View.prototype._preset = function () { // 模板引擎 this._tpl = $.tpl; }; /** * 获取模板目录 * @returns {string} 模板目录 */ View.prototype.getTplDir = function () { return __dirname; }; /** * 初始化核心 * @param {object} logger 日志管理器 */ View.prototype._initCore = async function (logger) { // 初始化依赖项 if (logger) { this.setLogger(logger); } this._tpl = new Tpl(); }; /** * 渲染html模板 * @param {string} html 模板 * @param {object} model 数据模型 * @returns {string} 渲染结果 */ View.prototype.render = async function (html, model) { // 参数校验 if (!html || typeof html !== 'string') { throw new TypeError('模板必须是非空字符串'); } if (model && typeof model !== 'object') { throw new TypeError('数据模型必须是对象'); } // 渲染模板 return this._tpl.render(html, model); }; /** * 渲染html模板文件 * @param {string} file 模板文件 * @param {object} model 数据模型 * @returns {string} 渲染结果 */ View.prototype.view = async function (file, model) { // 参数校验 if (!file || typeof file !== 'string') { throw new TypeError('模板文件必须是非空字符串'); } if (model && typeof model !== 'object') { throw new TypeError('数据模型必须是对象'); } // 渲染模板文件 return this._tpl.view(file, model); }; exports.View = View;